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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
750,525
|
defines.h
|
shiretu_crtmpserver/sources/common/include/defines.h
|
//DO NOT EDIT THIS FILE
//THIS FILE IS GENERATED
#ifndef DEFINES_H_
#define DEFINES_H_
#define AM "applicationMessage"
#define AM_LEN 18
#define AMF3_TRAITS "____traits____"
#define AMF3_TRAITS_LEN 14
#define AMF3_TRAITS_CLASSNAME "____class_name____"
#define AMF3_TRAITS_CLASSNAME_LEN 18
#define AMF3_TRAITS_DYNAMIC "____isDynamic____"
#define AMF3_TRAITS_DYNAMIC_LEN 17
#define AM_CONNECTIONID "connectionId"
#define AM_CONNECTIONID_LEN 12
#define AM_MESSAGEID "messageId"
#define AM_MESSAGEID_LEN 9
#define AM_PAYLOAD "payload"
#define AM_PAYLOAD_LEN 7
#define AM_PAYLOADTYPE "payloadType"
#define AM_PAYLOADTYPE_LEN 11
#define AM_SERVERID "serverId"
#define AM_SERVERID_LEN 8
#define BRANDING_BANNER "C++ RTMP Media Server (www.rtmpd.com)"
#define BRANDING_BANNER_LEN 37
#define BRANDING_COMPANY_NAME "C++ RTMP"
#define BRANDING_COMPANY_NAME_LEN 8
#define BRANDING_EMAIL "contact@rtmpd.com"
#define BRANDING_EMAIL_LEN 17
#define BRANDING_PRODUCT_NAME "C++ RTMP Media Server"
#define BRANDING_PRODUCT_NAME_LEN 21
#define BRANDING_WEB "www.rtmpd.com"
#define BRANDING_WEB_LEN 13
#define BRANDING_WEB_HTTP "http://www.rtmpd.com"
#define BRANDING_WEB_HTTP_LEN 20
#define CM "controlMessage"
#define CM_LEN 14
#define CM_OP "operation"
#define CM_OP_LEN 9
#define CM_OP_ATTACHONSTOINS "attachONSToINS"
#define CM_OP_ATTACHONSTOINS_LEN 14
#define CM_OP_CLIENTDISCONNECTED "clientDisconnected"
#define CM_OP_CLIENTDISCONNECTED_LEN 18
#define CM_OP_CLOSESTREAM "closeStream"
#define CM_OP_CLOSESTREAM_LEN 11
#define CM_OP_CREATEINS "createInboundNetworkStream"
#define CM_OP_CREATEINS_LEN 26
#define CM_OP_CREATEOFS "createOutboundFileStream"
#define CM_OP_CREATEOFS_LEN 24
#define CM_OP_CREATEONS "createOutboundNetworkStream"
#define CM_OP_CREATEONS_LEN 27
#define CM_OP_CREATESTREAM "createStream"
#define CM_OP_CREATESTREAM_LEN 12
#define CM_OP_DISCONNECTCLIENT "disconnectClient"
#define CM_OP_DISCONNECTCLIENT_LEN 16
#define CM_OP_ERROR "error"
#define CM_OP_ERROR_LEN 5
#define CM_OP_HELLOREQUEST "helloRequest"
#define CM_OP_HELLOREQUEST_LEN 12
#define CM_OP_HELLORESPONSE "helloResponse"
#define CM_OP_HELLORESPONSE_LEN 13
#define CM_OP_INSCREATED "inboundNetworkStreamCreated"
#define CM_OP_INSCREATED_LEN 27
#define CM_OP_OFSCREATED "outboundFileStreamCreated"
#define CM_OP_OFSCREATED_LEN 25
#define CM_OP_ONSCREATED "outboundNetworkStreamCreated"
#define CM_OP_ONSCREATED_LEN 28
#define CM_OP_ONSTOINSATTACHED "ONSToINSAttached"
#define CM_OP_ONSTOINSATTACHED_LEN 16
#define CM_OP_STREAMCLOSED "streamClosed"
#define CM_OP_STREAMCLOSED_LEN 12
#define CM_OP_STREAMCREATED "streamCreated"
#define CM_OP_STREAMCREATED_LEN 13
#define CM_PARAMS "parameters"
#define CM_PARAMS_LEN 10
#define CM_PARAMS_ATTACHONSTOINS_INSCONNECTIONID "INSConnectionId"
#define CM_PARAMS_ATTACHONSTOINS_INSCONNECTIONID_LEN 15
#define CM_PARAMS_ATTACHONSTOINS_INSSTREAMID "INSStreamId"
#define CM_PARAMS_ATTACHONSTOINS_INSSTREAMID_LEN 11
#define CM_PARAMS_ATTACHONSTOINS_ONSCONNECTIONID "ONSConnectionId"
#define CM_PARAMS_ATTACHONSTOINS_ONSCONNECTIONID_LEN 15
#define CM_PARAMS_ATTACHONSTOINS_ONSSTREAMID "ONSStreamId"
#define CM_PARAMS_ATTACHONSTOINS_ONSSTREAMID_LEN 11
#define CM_PARAMS_CLOSESTREAM_REQUESTCHANNELID "requestChannelId"
#define CM_PARAMS_CLOSESTREAM_REQUESTCHANNELID_LEN 16
#define CM_PARAMS_CLOSESTREAM_REQUESTID "requestId"
#define CM_PARAMS_CLOSESTREAM_REQUESTID_LEN 9
#define CM_PARAMS_CLOSESTREAM_REQUESTSTREAMID "requestStreamId"
#define CM_PARAMS_CLOSESTREAM_REQUESTSTREAMID_LEN 15
#define CM_PARAMS_CREATEINS_REQUESTCHANNELID "requestChannelId"
#define CM_PARAMS_CREATEINS_REQUESTCHANNELID_LEN 16
#define CM_PARAMS_CREATEINS_REQUESTID "requestId"
#define CM_PARAMS_CREATEINS_REQUESTID_LEN 9
#define CM_PARAMS_CREATEINS_REQUESTSTREAMID "requestStreamId"
#define CM_PARAMS_CREATEINS_REQUESTSTREAMID_LEN 15
#define CM_PARAMS_CREATEINS_STREAMNAME "streamName"
#define CM_PARAMS_CREATEINS_STREAMNAME_LEN 10
#define CM_PARAMS_CREATEOFS_APPEND "append"
#define CM_PARAMS_CREATEOFS_APPEND_LEN 6
#define CM_PARAMS_CREATEOFS_FILENAME "fileName"
#define CM_PARAMS_CREATEOFS_FILENAME_LEN 8
#define CM_PARAMS_CREATEOFS_STREAMID "streamId"
#define CM_PARAMS_CREATEOFS_STREAMID_LEN 8
#define CM_PARAMS_CREATEONS_REQUESTCHANNELID "requestChannelId"
#define CM_PARAMS_CREATEONS_REQUESTCHANNELID_LEN 16
#define CM_PARAMS_CREATEONS_REQUESTID "requestId"
#define CM_PARAMS_CREATEONS_REQUESTID_LEN 9
#define CM_PARAMS_CREATEONS_REQUESTSTREAMID "requestStreamId"
#define CM_PARAMS_CREATEONS_REQUESTSTREAMID_LEN 15
#define CM_PARAMS_CREATEONS_STREAMNAME "streamName"
#define CM_PARAMS_CREATEONS_STREAMNAME_LEN 10
#define CM_PARAMS_CREATESTREAM_REQUESTCHANNELID "requestChannelId"
#define CM_PARAMS_CREATESTREAM_REQUESTCHANNELID_LEN 16
#define CM_PARAMS_CREATESTREAM_REQUESTID "requestId"
#define CM_PARAMS_CREATESTREAM_REQUESTID_LEN 9
#define CM_PARAMS_CREATESTREAM_REQUESTSTREAMID "requestStreamId"
#define CM_PARAMS_CREATESTREAM_REQUESTSTREAMID_LEN 15
#define CM_PARAMS_ERROR_CODE "code"
#define CM_PARAMS_ERROR_CODE_LEN 4
#define CM_PARAMS_ERROR_CODE_INSINITFAILED 5
#define CM_PARAMS_ERROR_CODE_INVALIDRTMPHEADER 2
#define CM_PARAMS_ERROR_CODE_INVALIDSTREAMID 6
#define CM_PARAMS_ERROR_CODE_NEUTRALSTREAMINITFAILED 4
#define CM_PARAMS_ERROR_CODE_NOMOREFREESTREAMS 3
#define CM_PARAMS_ERROR_CODE_NYI 1
#define CM_PARAMS_ERROR_CODE_OFSINITFAILED 7
#define CM_PARAMS_ERROR_CODE_ONSINITFAILED 8
#define CM_PARAMS_ERROR_DESCRIPTION "description"
#define CM_PARAMS_ERROR_DESCRIPTION_LEN 11
#define CM_PARAMS_ERROR_EXTRAPARAMS "extraParams"
#define CM_PARAMS_ERROR_EXTRAPARAMS_LEN 11
#define CM_PARAMS_INSCREATED_STREAMID "streamId"
#define CM_PARAMS_INSCREATED_STREAMID_LEN 8
#define CM_PARAMS_INSCREATED_STREAMNAME "streamName"
#define CM_PARAMS_INSCREATED_STREAMNAME_LEN 10
#define CM_PARAMS_OFSCREATED_APPEND "append"
#define CM_PARAMS_OFSCREATED_APPEND_LEN 6
#define CM_PARAMS_OFSCREATED_FILENAME "filename"
#define CM_PARAMS_OFSCREATED_FILENAME_LEN 8
#define CM_PARAMS_OFSCREATED_STREAMID "streamId"
#define CM_PARAMS_OFSCREATED_STREAMID_LEN 8
#define CM_PARAMS_ONSCREATED_STREAMID "streamId"
#define CM_PARAMS_ONSCREATED_STREAMID_LEN 8
#define CM_PARAMS_ONSCREATED_STREAMNAME "streamName"
#define CM_PARAMS_ONSCREATED_STREAMNAME_LEN 10
#define CM_PARAMS_ONSTOINSATTACHED_INSCONNECTIONID "INSConnectionId"
#define CM_PARAMS_ONSTOINSATTACHED_INSCONNECTIONID_LEN 15
#define CM_PARAMS_ONSTOINSATTACHED_INSSTREAMID "INSStreamId"
#define CM_PARAMS_ONSTOINSATTACHED_INSSTREAMID_LEN 11
#define CM_PARAMS_ONSTOINSATTACHED_ONSCONNECTIONID "ONSConnectionId"
#define CM_PARAMS_ONSTOINSATTACHED_ONSCONNECTIONID_LEN 15
#define CM_PARAMS_ONSTOINSATTACHED_ONSSTREAMID "ONSStreamId"
#define CM_PARAMS_ONSTOINSATTACHED_ONSSTREAMID_LEN 11
#define CM_PARAMS_STREAMCLOSED_STREAMID "streamId"
#define CM_PARAMS_STREAMCLOSED_STREAMID_LEN 8
#define CM_PARAMS_STREAMCREATED_STREAMID "streamId"
#define CM_PARAMS_STREAMCREATED_STREAMID_LEN 8
#define CONF_ACCEPTORS "acceptors"
#define CONF_ACCEPTORS_LEN 9
#define CONF_ADDRESS "address"
#define CONF_ADDRESS_LEN 7
#define CONF_APPLICATIONS "applications"
#define CONF_APPLICATIONS_LEN 12
#define CONF_APPLICATIONS_ROOTDIRECTORY "rootDirectory"
#define CONF_APPLICATIONS_ROOTDIRECTORY_LEN 13
#define CONF_APPLICATION_ALIASES "aliases"
#define CONF_APPLICATION_ALIASES_LEN 7
#define CONF_APPLICATION_AUTH "authentication"
#define CONF_APPLICATION_AUTH_LEN 14
#define CONF_APPLICATION_AUTH_ENCODER_AGENTS "encoderAgents"
#define CONF_APPLICATION_AUTH_ENCODER_AGENTS_LEN 13
#define CONF_APPLICATION_AUTH_TYPE "type"
#define CONF_APPLICATION_AUTH_TYPE_LEN 4
#define CONF_APPLICATION_AUTH_TYPE_ADOBE "adobe"
#define CONF_APPLICATION_AUTH_TYPE_ADOBE_LEN 5
#define CONF_APPLICATION_AUTH_USERS_FILE "usersFile"
#define CONF_APPLICATION_AUTH_USERS_FILE_LEN 9
#define CONF_APPLICATION_CLIENTSIDEBUFFER "clientSideBuffer"
#define CONF_APPLICATION_CLIENTSIDEBUFFER_LEN 16
#define CONF_APPLICATION_DEFAULT "default"
#define CONF_APPLICATION_DEFAULT_LEN 7
#define CONF_APPLICATION_DELETE_APPLICATION_FUNCTION "deleteApplicationFunction"
#define CONF_APPLICATION_DELETE_APPLICATION_FUNCTION_LEN 25
#define CONF_APPLICATION_DELETE_FACTORY_FUNCTION "deleteFactoryFunction"
#define CONF_APPLICATION_DELETE_FACTORY_FUNCTION_LEN 21
#define CONF_APPLICATION_DESCRIPTION "description"
#define CONF_APPLICATION_DESCRIPTION_LEN 11
#define CONF_APPLICATION_DIRECTORY "appDir"
#define CONF_APPLICATION_DIRECTORY_LEN 6
#define CONF_APPLICATION_ENABLESTATS "enableStats"
#define CONF_APPLICATION_ENABLESTATS_LEN 11
#define CONF_APPLICATION_EXTERNALSEEKGENERATOR "externalSeekGenerator"
#define CONF_APPLICATION_EXTERNALSEEKGENERATOR_LEN 21
#define CONF_APPLICATION_HAS_STREAM_ALIASES "hasStreamAliases"
#define CONF_APPLICATION_HAS_STREAM_ALIASES_LEN 16
#define CONF_APPLICATION_INIT_APPLICATION_FUNCTION "initApplicationFunction"
#define CONF_APPLICATION_INIT_APPLICATION_FUNCTION_LEN 23
#define CONF_APPLICATION_INIT_FACTORY_FUNCTION "initFactoryFunction"
#define CONF_APPLICATION_INIT_FACTORY_FUNCTION_LEN 19
#define CONF_APPLICATION_KEYFRAMESEEK "keyframeSeek"
#define CONF_APPLICATION_KEYFRAMESEEK_LEN 12
#define CONF_APPLICATION_LIBRARY "library"
#define CONF_APPLICATION_LIBRARY_LEN 7
#define CONF_APPLICATION_MEDIAFOLDER "mediaFolder"
#define CONF_APPLICATION_MEDIAFOLDER_LEN 11
#define CONF_APPLICATION_MEDIASTORAGE "mediaStorage"
#define CONF_APPLICATION_MEDIASTORAGE_LEN 12
#define CONF_APPLICATION_METAFOLDER "metaFolder"
#define CONF_APPLICATION_METAFOLDER_LEN 10
#define CONF_APPLICATION_NAME "name"
#define CONF_APPLICATION_NAME_LEN 4
#define CONF_APPLICATION_RTCPDETECTIONINTERVAL "rtcpDetectionInterval"
#define CONF_APPLICATION_RTCPDETECTIONINTERVAL_LEN 21
#define CONF_APPLICATION_SEEKGRANULARITY "seekGranularity"
#define CONF_APPLICATION_SEEKGRANULARITY_LEN 15
#define CONF_APPLICATION_VALIDATEHANDSHAKE "validateHandshake"
#define CONF_APPLICATION_VALIDATEHANDSHAKE_LEN 17
#define CONF_BIND_ADDRESSES "bindAddresses"
#define CONF_BIND_ADDRESSES_LEN 13
#define CONF_CONFIGURATION "configuration"
#define CONF_CONFIGURATION_LEN 13
#define CONF_DAEMON "daemon"
#define CONF_DAEMON_LEN 6
#define CONF_IP "ip"
#define CONF_IP_LEN 2
#define CONF_LOG_APPENDERS "logAppenders"
#define CONF_LOG_APPENDERS_LEN 12
#define CONF_LOG_APPENDER_COLORED "colored"
#define CONF_LOG_APPENDER_COLORED_LEN 7
#define CONF_LOG_APPENDER_FILE_HISTORY_SIZE "fileHistorySize"
#define CONF_LOG_APPENDER_FILE_HISTORY_SIZE_LEN 15
#define CONF_LOG_APPENDER_FILE_LENGTH "fileLength"
#define CONF_LOG_APPENDER_FILE_LENGTH_LEN 10
#define CONF_LOG_APPENDER_FILE_NAME "fileName"
#define CONF_LOG_APPENDER_FILE_NAME_LEN 8
#define CONF_LOG_APPENDER_FORMAT "format"
#define CONF_LOG_APPENDER_FORMAT_LEN 6
#define CONF_LOG_APPENDER_LEVEL "level"
#define CONF_LOG_APPENDER_LEVEL_LEN 5
#define CONF_LOG_APPENDER_NAME "name"
#define CONF_LOG_APPENDER_NAME_LEN 4
#define CONF_LOG_APPENDER_NEW_LINE_CHARACTERS "newLineCharacters"
#define CONF_LOG_APPENDER_NEW_LINE_CHARACTERS_LEN 17
#define CONF_LOG_APPENDER_SINGLE_LINE "singleLine"
#define CONF_LOG_APPENDER_SINGLE_LINE_LEN 10
#define CONF_LOG_APPENDER_SPECIFIC_LEVEL "specificLevel"
#define CONF_LOG_APPENDER_SPECIFIC_LEVEL_LEN 13
#define CONF_LOG_APPENDER_TYPE "type"
#define CONF_LOG_APPENDER_TYPE_LEN 4
#define CONF_LOG_APPENDER_TYPE_COLORED_CONSOLE "coloredConsole"
#define CONF_LOG_APPENDER_TYPE_COLORED_CONSOLE_LEN 14
#define CONF_LOG_APPENDER_TYPE_CONSOLE "console"
#define CONF_LOG_APPENDER_TYPE_CONSOLE_LEN 7
#define CONF_LOG_APPENDER_TYPE_FILE "file"
#define CONF_LOG_APPENDER_TYPE_FILE_LEN 4
#define CONF_LOG_APPENDER_TYPE_SYSLOG "syslog"
#define CONF_LOG_APPENDER_TYPE_SYSLOG_LEN 6
#define CONF_NUMBER_OF_THREADS "numberOfThreads"
#define CONF_NUMBER_OF_THREADS_LEN 15
#define CONF_PATH_SEPARATOR "pathSeparator"
#define CONF_PATH_SEPARATOR_LEN 13
#define CONF_PORT "port"
#define CONF_PORT_LEN 4
#define CONF_PROTOCOL "protocol"
#define CONF_PROTOCOL_LEN 8
#define CONF_PROTOCOL_DYNAMICLINKLIBRARY "dynamiclinklibrary"
#define CONF_PROTOCOL_DYNAMICLINKLIBRARY_LEN 18
#define CONF_PROTOCOL_INBOUND_BIN_VARIANT "inboundBinVariant"
#define CONF_PROTOCOL_INBOUND_BIN_VARIANT_LEN 17
#define CONF_PROTOCOL_INBOUND_CLI_JSON "inboundJsonCli"
#define CONF_PROTOCOL_INBOUND_CLI_JSON_LEN 14
#define CONF_PROTOCOL_INBOUND_HTTP "inboundHttp"
#define CONF_PROTOCOL_INBOUND_HTTP_LEN 11
#define CONF_PROTOCOL_INBOUND_HTTPS_BIN_VARIANT "inboundHttpsBinVariant"
#define CONF_PROTOCOL_INBOUND_HTTPS_BIN_VARIANT_LEN 22
#define CONF_PROTOCOL_INBOUND_HTTPS_JSON_VARIANT "inboundHttpsJsonVariant"
#define CONF_PROTOCOL_INBOUND_HTTPS_JSON_VARIANT_LEN 23
#define CONF_PROTOCOL_INBOUND_HTTPS_XML_VARIANT "inboundHttpsXmlVariant"
#define CONF_PROTOCOL_INBOUND_HTTPS_XML_VARIANT_LEN 22
#define CONF_PROTOCOL_INBOUND_HTTP_BIN_VARIANT "inboundHttpBinVariant"
#define CONF_PROTOCOL_INBOUND_HTTP_BIN_VARIANT_LEN 21
#define CONF_PROTOCOL_INBOUND_HTTP_CLI_JSON "inboundHttpJsonCli"
#define CONF_PROTOCOL_INBOUND_HTTP_CLI_JSON_LEN 18
#define CONF_PROTOCOL_INBOUND_HTTP_JSON_VARIANT "inboundHttpJsonVariant"
#define CONF_PROTOCOL_INBOUND_HTTP_JSON_VARIANT_LEN 22
#define CONF_PROTOCOL_INBOUND_HTTP_XML_VARIANT "inboundHttpXmlVariant"
#define CONF_PROTOCOL_INBOUND_HTTP_XML_VARIANT_LEN 21
#define CONF_PROTOCOL_INBOUND_JSON_VARIANT "inboundJsonVariant"
#define CONF_PROTOCOL_INBOUND_JSON_VARIANT_LEN 18
#define CONF_PROTOCOL_INBOUND_LIVE_FLV "inboundLiveFlv"
#define CONF_PROTOCOL_INBOUND_LIVE_FLV_LEN 14
#define CONF_PROTOCOL_INBOUND_RTMP "inboundRtmp"
#define CONF_PROTOCOL_INBOUND_RTMP_LEN 11
#define CONF_PROTOCOL_INBOUND_RTMPS "inboundRtmps"
#define CONF_PROTOCOL_INBOUND_RTMPS_LEN 12
#define CONF_PROTOCOL_INBOUND_RTMPT "inboundRtmpt"
#define CONF_PROTOCOL_INBOUND_RTMPT_LEN 12
#define CONF_PROTOCOL_INBOUND_RTSP "inboundRtsp"
#define CONF_PROTOCOL_INBOUND_RTSP_LEN 11
#define CONF_PROTOCOL_INBOUND_RTSP_RTP "inboundRtspRtp"
#define CONF_PROTOCOL_INBOUND_RTSP_RTP_LEN 14
#define CONF_PROTOCOL_INBOUND_TCP_TS "inboundTcpTs"
#define CONF_PROTOCOL_INBOUND_TCP_TS_LEN 12
#define CONF_PROTOCOL_INBOUND_UDP_RTP "inboundUdpRtp"
#define CONF_PROTOCOL_INBOUND_UDP_RTP_LEN 13
#define CONF_PROTOCOL_INBOUND_UDP_TS "inboundUdpTs"
#define CONF_PROTOCOL_INBOUND_UDP_TS_LEN 12
#define CONF_PROTOCOL_INBOUND_XML_VARIANT "inboundXmlVariant"
#define CONF_PROTOCOL_INBOUND_XML_VARIANT_LEN 17
#define CONF_PROTOCOL_OUTBOUND_BIN_VARIANT "outboundBinVariant"
#define CONF_PROTOCOL_OUTBOUND_BIN_VARIANT_LEN 18
#define CONF_PROTOCOL_OUTBOUND_HTTP "outboundHttp"
#define CONF_PROTOCOL_OUTBOUND_HTTP_LEN 12
#define CONF_PROTOCOL_OUTBOUND_HTTPS_BIN_VARIANT "outboundHttpsBinVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTPS_BIN_VARIANT_LEN 23
#define CONF_PROTOCOL_OUTBOUND_HTTPS_JSON_VARIANT "outboundHttpsJsonVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTPS_JSON_VARIANT_LEN 24
#define CONF_PROTOCOL_OUTBOUND_HTTPS_XML_VARIANT "outboundHttpsXmlVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTPS_XML_VARIANT_LEN 23
#define CONF_PROTOCOL_OUTBOUND_HTTP_BIN_VARIANT "outboundHttpBinVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTP_BIN_VARIANT_LEN 22
#define CONF_PROTOCOL_OUTBOUND_HTTP_JSON_VARIANT "outboundHttpJsonVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTP_JSON_VARIANT_LEN 23
#define CONF_PROTOCOL_OUTBOUND_HTTP_XML_VARIANT "outboundHttpXmlVariant"
#define CONF_PROTOCOL_OUTBOUND_HTTP_XML_VARIANT_LEN 22
#define CONF_PROTOCOL_OUTBOUND_JSON_VARIANT "outboundJsonVariant"
#define CONF_PROTOCOL_OUTBOUND_JSON_VARIANT_LEN 19
#define CONF_PROTOCOL_OUTBOUND_LIVE_FLV "outboundLiveFlv"
#define CONF_PROTOCOL_OUTBOUND_LIVE_FLV_LEN 15
#define CONF_PROTOCOL_OUTBOUND_RTMP "outboundRtmp"
#define CONF_PROTOCOL_OUTBOUND_RTMP_LEN 12
#define CONF_PROTOCOL_OUTBOUND_RTMPE "outboundRtmpe"
#define CONF_PROTOCOL_OUTBOUND_RTMPE_LEN 13
#define CONF_PROTOCOL_OUTBOUND_RTMPS "outboundRtmps"
#define CONF_PROTOCOL_OUTBOUND_RTMPS_LEN 13
#define CONF_PROTOCOL_OUTBOUND_RTMPT "outboundRtmpt"
#define CONF_PROTOCOL_OUTBOUND_RTMPT_LEN 13
#define CONF_PROTOCOL_OUTBOUND_XML_VARIANT "outboundXmlVariant"
#define CONF_PROTOCOL_OUTBOUND_XML_VARIANT_LEN 18
#define CONF_PROTOCOL_RTP_NAT_TRAVERSAL "rtpNatTraversal"
#define CONF_PROTOCOL_RTP_NAT_TRAVERSAL_LEN 15
#define CONF_PROTOCOL_RTSP_RTCP "inboundRtspRtcp"
#define CONF_PROTOCOL_RTSP_RTCP_LEN 15
#define CONF_PROTOCOL_TCP_PASSTHROUGH "tcpPassThrough"
#define CONF_PROTOCOL_TCP_PASSTHROUGH_LEN 14
#define CONF_PROTOCOL_UDP_PASSTHROUGH "udpPassThrough"
#define CONF_PROTOCOL_UDP_PASSTHROUGH_LEN 14
#define CONF_PROTOCOL_UDP_RTCP "inboundUdpRtcp"
#define CONF_PROTOCOL_UDP_RTCP_LEN 14
#define CONF_SSL_CERT "sslCert"
#define CONF_SSL_CERT_LEN 7
#define CONF_SSL_CIPHERSUITE "cipherSuite"
#define CONF_SSL_CIPHERSUITE_LEN 11
#define CONF_SSL_KEY "sslKey"
#define CONF_SSL_KEY_LEN 6
#define CONF_STORAGE_PATH "storagePath"
#define CONF_STORAGE_PATH_LEN 11
#define HTTP_FIRST_LINE "firstLine"
#define HTTP_FIRST_LINE_LEN 9
#define HTTP_FULL_URL "fullUrl"
#define HTTP_FULL_URL_LEN 7
#define HTTP_HEADERS "headers"
#define HTTP_HEADERS_LEN 7
#define HTTP_HEADERS_AUTORIZATION "Authorization"
#define HTTP_HEADERS_AUTORIZATION_LEN 13
#define HTTP_HEADERS_CACHE_CONTROL "Cache-Control"
#define HTTP_HEADERS_CACHE_CONTROL_LEN 13
#define HTTP_HEADERS_CACHE_CONTROL_NO_CACHE "no-cache"
#define HTTP_HEADERS_CACHE_CONTROL_NO_CACHE_LEN 8
#define HTTP_HEADERS_CONNECTION "Connection"
#define HTTP_HEADERS_CONNECTION_LEN 10
#define HTTP_HEADERS_CONNECTION_CLOSE "close"
#define HTTP_HEADERS_CONNECTION_CLOSE_LEN 5
#define HTTP_HEADERS_CONNECTION_KEEP_ALIVE "Keep-Alive"
#define HTTP_HEADERS_CONNECTION_KEEP_ALIVE_LEN 10
#define HTTP_HEADERS_CONTENT_LENGTH "Content-Length"
#define HTTP_HEADERS_CONTENT_LENGTH_LEN 14
#define HTTP_HEADERS_CONTENT_TYPE "Content-Type"
#define HTTP_HEADERS_CONTENT_TYPE_LEN 12
#define HTTP_HEADERS_CONTENT_TYPE_XFCS "application/x-fcs"
#define HTTP_HEADERS_CONTENT_TYPE_XFCS_LEN 17
#define HTTP_HEADERS_HOST "Host"
#define HTTP_HEADERS_HOST_LEN 4
#define HTTP_HEADERS_SERVER "Server"
#define HTTP_HEADERS_SERVER_LEN 6
#define HTTP_HEADERS_SERVER_US "C++ RTMP Media Server (www.rtmpd.com)"
#define HTTP_HEADERS_SERVER_US_LEN 37
#define HTTP_HEADERS_TRANSFER_ENCODING "Transfer-Encoding"
#define HTTP_HEADERS_TRANSFER_ENCODING_LEN 17
#define HTTP_HEADERS_TRANSFER_ENCODING_CHUNKED "chunked"
#define HTTP_HEADERS_TRANSFER_ENCODING_CHUNKED_LEN 7
#define HTTP_HEADERS_USER_AGENT "User-Agent"
#define HTTP_HEADERS_USER_AGENT_LEN 10
#define HTTP_HEADERS_WWWAUTHENTICATE "WWW-Authenticate"
#define HTTP_HEADERS_WWWAUTHENTICATE_LEN 16
#define HTTP_HEADERS_X_POWERED_BY "X-Powered-By"
#define HTTP_HEADERS_X_POWERED_BY_LEN 12
#define HTTP_HEADERS_X_POWERED_BY_US "C++ RTMP Media Server (www.rtmpd.com)"
#define HTTP_HEADERS_X_POWERED_BY_US_LEN 37
#define HTTP_METHOD "method"
#define HTTP_METHOD_LEN 6
#define HTTP_METHOD_GET "GET"
#define HTTP_METHOD_GET_LEN 3
#define HTTP_METHOD_POST "POST"
#define HTTP_METHOD_POST_LEN 4
#define HTTP_PARAMETERS "parameters"
#define HTTP_PARAMETERS_LEN 10
#define HTTP_STATUS_CODE "statusCode"
#define HTTP_STATUS_CODE_LEN 10
#define HTTP_STATUS_CODE_200 "200"
#define HTTP_STATUS_CODE_200_LEN 3
#define HTTP_STATUS_CODE_REASON "reason"
#define HTTP_STATUS_CODE_REASON_LEN 6
#define HTTP_URL "url"
#define HTTP_URL_LEN 3
#define HTTP_VERSION "version"
#define HTTP_VERSION_LEN 7
#define HTTP_VERSION_1_0 "HTTP/1.0"
#define HTTP_VERSION_1_0_LEN 8
#define HTTP_VERSION_1_1 "HTTP/1.1"
#define HTTP_VERSION_1_1_LEN 8
#define KEYFRAMES_PER_SECOND 2
#define MEDIA_TYPE_F4V "f4v"
#define MEDIA_TYPE_F4V_LEN 3
#define MEDIA_TYPE_FLV "flv"
#define MEDIA_TYPE_FLV_LEN 3
#define MEDIA_TYPE_LIVE_OR_FLV "liveOrFlv"
#define MEDIA_TYPE_LIVE_OR_FLV_LEN 9
#define MEDIA_TYPE_M4A "m4a"
#define MEDIA_TYPE_M4A_LEN 3
#define MEDIA_TYPE_M4V "m4v"
#define MEDIA_TYPE_M4V_LEN 3
#define MEDIA_TYPE_META "meta"
#define MEDIA_TYPE_META_LEN 4
#define MEDIA_TYPE_MOV "mov"
#define MEDIA_TYPE_MOV_LEN 3
#define MEDIA_TYPE_MP3 "mp3"
#define MEDIA_TYPE_MP3_LEN 3
#define MEDIA_TYPE_MP4 "mp4"
#define MEDIA_TYPE_MP4_LEN 3
#define MEDIA_TYPE_SEEK "seek"
#define MEDIA_TYPE_SEEK_LEN 4
#define MEDIA_TYPE_STATS "stats"
#define MEDIA_TYPE_STATS_LEN 5
#define MEDIA_TYPE_TS "ts"
#define MEDIA_TYPE_TS_LEN 2
#define META_MEDIA_META "meta"
#define META_MEDIA_META_LEN 4
#define META_MEDIA_SEEK "seek"
#define META_MEDIA_SEEK_LEN 4
#define META_MEDIA_TYPE "streamType"
#define META_MEDIA_TYPE_LEN 10
#define PM_APPEND 2
#define PM_APPEND_STRING "append"
#define PM_APPEND_STRING_LEN 6
#define PM_LIVE 3
#define PM_LIVE_STRING "live"
#define PM_LIVE_STRING_LEN 4
#define PM_RECORD 1
#define PM_RECORD_STRING "record"
#define PM_RECORD_STRING_LEN 6
#define PM_UNKNOWN 0
#define PM_UNKNOWN_STRING "unknown"
#define PM_UNKNOWN_STRING_LEN 7
#define RM "rtmpMessage"
#define RM_LEN 11
#define RM_ABORTMESSAGE "abortMessage"
#define RM_ABORTMESSAGE_LEN 12
#define RM_ACK "ack"
#define RM_ACK_LEN 3
#define RM_CHUNKSIZE "chunkSize"
#define RM_CHUNKSIZE_LEN 9
#define RM_FLEXSHAREDOBJECT "flexSharedObject"
#define RM_FLEXSHAREDOBJECT_LEN 16
#define RM_FLEXSHAREDOBJECTPRIMITIVE_PAYLOAD "fsoPayload"
#define RM_FLEXSHAREDOBJECTPRIMITIVE_PAYLOAD_LEN 10
#define RM_FLEXSHAREDOBJECTPRIMITIVE_RAWLENGTH "fsoRawLength"
#define RM_FLEXSHAREDOBJECTPRIMITIVE_RAWLENGTH_LEN 12
#define RM_FLEXSHAREDOBJECTPRIMITIVE_TYPE "fsoType"
#define RM_FLEXSHAREDOBJECTPRIMITIVE_TYPE_LEN 7
#define RM_FLEXSHAREDOBJECT_NAME "fsoName"
#define RM_FLEXSHAREDOBJECT_NAME_LEN 7
#define RM_FLEXSHAREDOBJECT_PERSISTENCE "fsoPersistence"
#define RM_FLEXSHAREDOBJECT_PERSISTENCE_LEN 14
#define RM_FLEXSHAREDOBJECT_PRIMITIVES "fsoPrimitives"
#define RM_FLEXSHAREDOBJECT_PRIMITIVES_LEN 13
#define RM_FLEXSHAREDOBJECT_VERSION "fsoVersion"
#define RM_FLEXSHAREDOBJECT_VERSION_LEN 10
#define RM_FLEXSTREAMSEND "flexStreamSend"
#define RM_FLEXSTREAMSEND_LEN 14
#define RM_FLEXSTREAMSEND_PARAMS "params"
#define RM_FLEXSTREAMSEND_PARAMS_LEN 6
#define RM_FLEXSTREAMSEND_UNKNOWNBYTE "unknownByte"
#define RM_FLEXSTREAMSEND_UNKNOWNBYTE_LEN 11
#define RM_HEADER "header"
#define RM_HEADER_LEN 6
#define RM_HEADER_CHANNELID "channelId"
#define RM_HEADER_CHANNELID_LEN 9
#define RM_HEADER_HEADERTYPE "headerType"
#define RM_HEADER_HEADERTYPE_LEN 10
#define RM_HEADER_ISABSOLUTE "isAbsolute"
#define RM_HEADER_ISABSOLUTE_LEN 10
#define RM_HEADER_MESSAGELENGTH "messageLength"
#define RM_HEADER_MESSAGELENGTH_LEN 13
#define RM_HEADER_MESSAGETYPE "messageType"
#define RM_HEADER_MESSAGETYPE_LEN 11
#define RM_HEADER_MESSAGETYPE_ABORTMESSAGE 2
#define RM_HEADER_MESSAGETYPE_ACK 3
#define RM_HEADER_MESSAGETYPE_AGGREGATE 22
#define RM_HEADER_MESSAGETYPE_AUDIODATA 8
#define RM_HEADER_MESSAGETYPE_CHUNKSIZE 1
#define RM_HEADER_MESSAGETYPE_FLEX 17
#define RM_HEADER_MESSAGETYPE_FLEXSHAREDOBJECT 16
#define RM_HEADER_MESSAGETYPE_FLEXSTREAMSEND 15
#define RM_HEADER_MESSAGETYPE_INVOKE 20
#define RM_HEADER_MESSAGETYPE_NOTIFY 18
#define RM_HEADER_MESSAGETYPE_PEERBW 6
#define RM_HEADER_MESSAGETYPE_SHAREDOBJECT 19
#define RM_HEADER_MESSAGETYPE_USRCTRL 4
#define RM_HEADER_MESSAGETYPE_VIDEODATA 9
#define RM_HEADER_MESSAGETYPE_WINACKSIZE 5
#define RM_HEADER_ORIGINALHEADERSIZE "originalHeaderSize"
#define RM_HEADER_ORIGINALHEADERSIZE_LEN 18
#define RM_HEADER_STREAMID "streamId"
#define RM_HEADER_STREAMID_LEN 8
#define RM_HEADER_TIMESTAMP "timestamp"
#define RM_HEADER_TIMESTAMP_LEN 9
#define RM_INVOKE "invoke"
#define RM_INVOKE_LEN 6
#define RM_INVOKE_FUNCTION "functionName"
#define RM_INVOKE_FUNCTION_LEN 12
#define RM_INVOKE_FUNCTION_CHECKBANDWIDTH "checkBandwidth"
#define RM_INVOKE_FUNCTION_CHECKBANDWIDTH_LEN 14
#define RM_INVOKE_FUNCTION_CLOSE "close"
#define RM_INVOKE_FUNCTION_CLOSE_LEN 5
#define RM_INVOKE_FUNCTION_CLOSESTREAM "closeStream"
#define RM_INVOKE_FUNCTION_CLOSESTREAM_LEN 11
#define RM_INVOKE_FUNCTION_CONNECT "connect"
#define RM_INVOKE_FUNCTION_CONNECT_LEN 7
#define RM_INVOKE_FUNCTION_CREATESTREAM "createStream"
#define RM_INVOKE_FUNCTION_CREATESTREAM_LEN 12
#define RM_INVOKE_FUNCTION_DELETESTREAM "deleteStream"
#define RM_INVOKE_FUNCTION_DELETESTREAM_LEN 12
#define RM_INVOKE_FUNCTION_ERROR "_error"
#define RM_INVOKE_FUNCTION_ERROR_LEN 6
#define RM_INVOKE_FUNCTION_FCPUBLISH "FCPublish"
#define RM_INVOKE_FUNCTION_FCPUBLISH_LEN 9
#define RM_INVOKE_FUNCTION_FCPUNUBLISH "FCUnpublish"
#define RM_INVOKE_FUNCTION_FCPUNUBLISH_LEN 11
#define RM_INVOKE_FUNCTION_FCSUBSCRIBE "FCSubscribe"
#define RM_INVOKE_FUNCTION_FCSUBSCRIBE_LEN 11
#define RM_INVOKE_FUNCTION_GETSTREAMLENGTH "getStreamLength"
#define RM_INVOKE_FUNCTION_GETSTREAMLENGTH_LEN 15
#define RM_INVOKE_FUNCTION_ONBWCHECK "onBWCheck"
#define RM_INVOKE_FUNCTION_ONBWCHECK_LEN 9
#define RM_INVOKE_FUNCTION_ONBWDONE "onBWDone"
#define RM_INVOKE_FUNCTION_ONBWDONE_LEN 8
#define RM_INVOKE_FUNCTION_ONFCPUBLISH "onFCPublish"
#define RM_INVOKE_FUNCTION_ONFCPUBLISH_LEN 11
#define RM_INVOKE_FUNCTION_ONSTATUS "onStatus"
#define RM_INVOKE_FUNCTION_ONSTATUS_LEN 8
#define RM_INVOKE_FUNCTION_PAUSE "pause"
#define RM_INVOKE_FUNCTION_PAUSE_LEN 5
#define RM_INVOKE_FUNCTION_PAUSERAW "pauseRaw"
#define RM_INVOKE_FUNCTION_PAUSERAW_LEN 8
#define RM_INVOKE_FUNCTION_PLAY "play"
#define RM_INVOKE_FUNCTION_PLAY_LEN 4
#define RM_INVOKE_FUNCTION_PUBLISH "publish"
#define RM_INVOKE_FUNCTION_PUBLISH_LEN 7
#define RM_INVOKE_FUNCTION_RELEASESTREAM "releaseStream"
#define RM_INVOKE_FUNCTION_RELEASESTREAM_LEN 13
#define RM_INVOKE_FUNCTION_RESULT "_result"
#define RM_INVOKE_FUNCTION_RESULT_LEN 7
#define RM_INVOKE_FUNCTION_SEEK "seek"
#define RM_INVOKE_FUNCTION_SEEK_LEN 4
#define RM_INVOKE_ID "id"
#define RM_INVOKE_ID_LEN 2
#define RM_INVOKE_IS_FLEX "isFlex"
#define RM_INVOKE_IS_FLEX_LEN 6
#define RM_INVOKE_PARAMS "parameters"
#define RM_INVOKE_PARAMS_LEN 10
#define RM_INVOKE_PARAMS_CONNECT_APP "app"
#define RM_INVOKE_PARAMS_CONNECT_APP_LEN 3
#define RM_INVOKE_PARAMS_CONNECT_AUDIOCODECS "audioCodecs"
#define RM_INVOKE_PARAMS_CONNECT_AUDIOCODECS_LEN 11
#define RM_INVOKE_PARAMS_CONNECT_CAPABILITIES "capabilities"
#define RM_INVOKE_PARAMS_CONNECT_CAPABILITIES_LEN 12
#define RM_INVOKE_PARAMS_CONNECT_FLASHVER "flashVer"
#define RM_INVOKE_PARAMS_CONNECT_FLASHVER_LEN 8
#define RM_INVOKE_PARAMS_CONNECT_FPAD "fpad"
#define RM_INVOKE_PARAMS_CONNECT_FPAD_LEN 4
#define RM_INVOKE_PARAMS_CONNECT_PAGEURL "pageUrl"
#define RM_INVOKE_PARAMS_CONNECT_PAGEURL_LEN 7
#define RM_INVOKE_PARAMS_CONNECT_SWFURL "swfUrl"
#define RM_INVOKE_PARAMS_CONNECT_SWFURL_LEN 6
#define RM_INVOKE_PARAMS_CONNECT_TCURL "tcUrl"
#define RM_INVOKE_PARAMS_CONNECT_TCURL_LEN 5
#define RM_INVOKE_PARAMS_CONNECT_VIDEOCODECS "videoCodecs"
#define RM_INVOKE_PARAMS_CONNECT_VIDEOCODECS_LEN 11
#define RM_INVOKE_PARAMS_CONNECT_VIDEOFUNCTION "videoFunction"
#define RM_INVOKE_PARAMS_CONNECT_VIDEOFUNCTION_LEN 13
#define RM_INVOKE_PARAMS_ONSTATUS_CLIENTID "clientid"
#define RM_INVOKE_PARAMS_ONSTATUS_CLIENTID_LEN 8
#define RM_INVOKE_PARAMS_ONSTATUS_CODE "code"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_LEN 4
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPAUSENOTIFY "NetStream.Pause.Notify"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPAUSENOTIFY_LEN 22
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPLAYRESET "NetStream.Play.Reset"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPLAYRESET_LEN 20
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPLAYSTART "NetStream.Play.Start"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPLAYSTART_LEN 20
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPUBLISHSTART "NetStream.Publish.Start"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMPUBLISHSTART_LEN 23
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMSEEKNOTIFY "NetStream.Seek.Notify"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMSEEKNOTIFY_LEN 21
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMUNPAUSENOTIFY "NetStream.Unpause.Notify"
#define RM_INVOKE_PARAMS_ONSTATUS_CODE_NETSTREAMUNPAUSENOTIFY_LEN 24
#define RM_INVOKE_PARAMS_ONSTATUS_DESCRIPTION "description"
#define RM_INVOKE_PARAMS_ONSTATUS_DESCRIPTION_LEN 11
#define RM_INVOKE_PARAMS_ONSTATUS_DETAILS "details"
#define RM_INVOKE_PARAMS_ONSTATUS_DETAILS_LEN 7
#define RM_INVOKE_PARAMS_ONSTATUS_LEVEL "level"
#define RM_INVOKE_PARAMS_ONSTATUS_LEVEL_LEN 5
#define RM_INVOKE_PARAMS_ONSTATUS_LEVEL_STATUS "status"
#define RM_INVOKE_PARAMS_ONSTATUS_LEVEL_STATUS_LEN 6
#define RM_INVOKE_PARAMS_PUBLISH_TYPEAPPEND "append"
#define RM_INVOKE_PARAMS_PUBLISH_TYPEAPPEND_LEN 6
#define RM_INVOKE_PARAMS_PUBLISH_TYPERECORD "record"
#define RM_INVOKE_PARAMS_PUBLISH_TYPERECORD_LEN 6
#define RM_INVOKE_PARAMS_RESULT_CODE "code"
#define RM_INVOKE_PARAMS_RESULT_CODE_LEN 4
#define RM_INVOKE_PARAMS_RESULT_CODE_NETCONNECTIONCONNECTREJECTED "NetConnection.Connect.Rejected"
#define RM_INVOKE_PARAMS_RESULT_CODE_NETCONNECTIONCONNECTREJECTED_LEN 30
#define RM_INVOKE_PARAMS_RESULT_CODE_NETCONNECTIONCONNECTSUCCESS "NetConnection.Connect.Success"
#define RM_INVOKE_PARAMS_RESULT_CODE_NETCONNECTIONCONNECTSUCCESS_LEN 29
#define RM_INVOKE_PARAMS_RESULT_DESCRIPTION "description"
#define RM_INVOKE_PARAMS_RESULT_DESCRIPTION_LEN 11
#define RM_INVOKE_PARAMS_RESULT_DESCRIPTION_CONNECTIONSUCCEEDED "Connection succeeded"
#define RM_INVOKE_PARAMS_RESULT_DESCRIPTION_CONNECTIONSUCCEEDED_LEN 20
#define RM_INVOKE_PARAMS_RESULT_LEVEL "level"
#define RM_INVOKE_PARAMS_RESULT_LEVEL_LEN 5
#define RM_INVOKE_PARAMS_RESULT_LEVEL_ERROR "error"
#define RM_INVOKE_PARAMS_RESULT_LEVEL_ERROR_LEN 5
#define RM_INVOKE_PARAMS_RESULT_LEVEL_STATUS "status"
#define RM_INVOKE_PARAMS_RESULT_LEVEL_STATUS_LEN 6
#define RM_INVOKE_PARAMS_RESULT_OBJECTENCODING "objectEncoding"
#define RM_INVOKE_PARAMS_RESULT_OBJECTENCODING_LEN 14
#define RM_NOTIFY "notify"
#define RM_NOTIFY_LEN 6
#define RM_NOTIFY_PARAMS "params"
#define RM_NOTIFY_PARAMS_LEN 6
#define RM_PEERBW "peerBw"
#define RM_PEERBW_LEN 6
#define RM_PEERBW_TYPE "kind"
#define RM_PEERBW_TYPE_LEN 4
#define RM_PEERBW_TYPE_DYNAMIC 2
#define RM_PEERBW_TYPE_HARD 0
#define RM_PEERBW_TYPE_SOFT 1
#define RM_PEERBW_VALUE "value"
#define RM_PEERBW_VALUE_LEN 5
#define RM_SHAREDOBJECT "sharedObject"
#define RM_SHAREDOBJECT_LEN 12
#define RM_SHAREDOBJECTPRIMITIVE_PAYLOAD "payload"
#define RM_SHAREDOBJECTPRIMITIVE_PAYLOAD_LEN 7
#define RM_SHAREDOBJECTPRIMITIVE_RAWLENGTH "rawLength"
#define RM_SHAREDOBJECTPRIMITIVE_RAWLENGTH_LEN 9
#define RM_SHAREDOBJECTPRIMITIVE_STRTYPE "strType"
#define RM_SHAREDOBJECTPRIMITIVE_STRTYPE_LEN 7
#define RM_SHAREDOBJECTPRIMITIVE_TYPE "type"
#define RM_SHAREDOBJECTPRIMITIVE_TYPE_LEN 4
#define RM_SHAREDOBJECT_NAME "name"
#define RM_SHAREDOBJECT_NAME_LEN 4
#define RM_SHAREDOBJECT_PERSISTENCE "persistence"
#define RM_SHAREDOBJECT_PERSISTENCE_LEN 11
#define RM_SHAREDOBJECT_PRIMITIVES "primitives"
#define RM_SHAREDOBJECT_PRIMITIVES_LEN 10
#define RM_SHAREDOBJECT_VERSION "version"
#define RM_SHAREDOBJECT_VERSION_LEN 7
#define RM_USRCTRL "usrCtrl"
#define RM_USRCTRL_LEN 7
#define RM_USRCTRL_BUFFLEN "buffLen"
#define RM_USRCTRL_BUFFLEN_LEN 7
#define RM_USRCTRL_PING "ping"
#define RM_USRCTRL_PING_LEN 4
#define RM_USRCTRL_PONG "pong"
#define RM_USRCTRL_PONG_LEN 4
#define RM_USRCTRL_STREAMID "streamId"
#define RM_USRCTRL_STREAMID_LEN 8
#define RM_USRCTRL_TIMESTAMP "timestamp"
#define RM_USRCTRL_TIMESTAMP_LEN 9
#define RM_USRCTRL_TYPE "type"
#define RM_USRCTRL_TYPE_LEN 4
#define RM_USRCTRL_TYPE_PING_REQUEST 6
#define RM_USRCTRL_TYPE_PING_RESPONSE 7
#define RM_USRCTRL_TYPE_STREAM_BEGIN 0
#define RM_USRCTRL_TYPE_STREAM_DRY 2
#define RM_USRCTRL_TYPE_STREAM_EOF 1
#define RM_USRCTRL_TYPE_STREAM_IS_RECORDED 4
#define RM_USRCTRL_TYPE_STREAM_SET_BUFFER_LENGTH 3
#define RM_USRCTRL_TYPE_STRING "typeString"
#define RM_USRCTRL_TYPE_STRING_LEN 10
#define RM_USRCTRL_TYPE_UNKNOWN1 31
#define RM_USRCTRL_TYPE_UNKNOWN2 32
#define RM_USRCTRL_UNKNOWN_U32 "unknownU32"
#define RM_USRCTRL_UNKNOWN_U32_LEN 10
#define RM_WINACKSIZE "winAckSize"
#define RM_WINACKSIZE_LEN 10
#define RTSP_FIRST_LINE "firstLine"
#define RTSP_FIRST_LINE_LEN 9
#define RTSP_HEADERS "headers"
#define RTSP_HEADERS_LEN 7
#define RTSP_HEADERS_ACCEPT "Accept"
#define RTSP_HEADERS_ACCEPT_LEN 6
#define RTSP_HEADERS_ACCEPT_APPLICATIONSDP "application/sdp"
#define RTSP_HEADERS_ACCEPT_APPLICATIONSDP_LEN 15
#define RTSP_HEADERS_AUTHORIZATION "Authorization"
#define RTSP_HEADERS_AUTHORIZATION_LEN 13
#define RTSP_HEADERS_CONTENT_BASE "Content-Base"
#define RTSP_HEADERS_CONTENT_BASE_LEN 12
#define RTSP_HEADERS_CONTENT_LENGTH "Content-Length"
#define RTSP_HEADERS_CONTENT_LENGTH_LEN 14
#define RTSP_HEADERS_CONTENT_TYPE "Content-Type"
#define RTSP_HEADERS_CONTENT_TYPE_LEN 12
#define RTSP_HEADERS_CSEQ "CSeq"
#define RTSP_HEADERS_CSEQ_LEN 4
#define RTSP_HEADERS_PUBLIC "Public"
#define RTSP_HEADERS_PUBLIC_LEN 6
#define RTSP_HEADERS_RANGE "Range"
#define RTSP_HEADERS_RANGE_LEN 5
#define RTSP_HEADERS_RANGE_NOW "now"
#define RTSP_HEADERS_RANGE_NOW_LEN 3
#define RTSP_HEADERS_RTP_INFO "RTP-Info"
#define RTSP_HEADERS_RTP_INFO_LEN 8
#define RTSP_HEADERS_SERVER "Server"
#define RTSP_HEADERS_SERVER_LEN 6
#define RTSP_HEADERS_SERVER_US "C++ RTMP Media Server (www.rtmpd.com)"
#define RTSP_HEADERS_SERVER_US_LEN 37
#define RTSP_HEADERS_SESSION "Session"
#define RTSP_HEADERS_SESSION_LEN 7
#define RTSP_HEADERS_TRANSPORT "Transport"
#define RTSP_HEADERS_TRANSPORT_LEN 9
#define RTSP_HEADERS_X_POWERED_BY "X-Powered-By"
#define RTSP_HEADERS_X_POWERED_BY_LEN 12
#define RTSP_HEADERS_X_POWERED_BY_US "C++ RTMP Media Server (www.rtmpd.com)"
#define RTSP_HEADERS_X_POWERED_BY_US_LEN 37
#define RTSP_METHOD "method"
#define RTSP_METHOD_LEN 6
#define RTSP_METHOD_ANNOUNCE "ANNOUNCE"
#define RTSP_METHOD_ANNOUNCE_LEN 8
#define RTSP_METHOD_DESCRIBE "DESCRIBE"
#define RTSP_METHOD_DESCRIBE_LEN 8
#define RTSP_METHOD_GET_PARAMETER "GET_PARAMETER"
#define RTSP_METHOD_GET_PARAMETER_LEN 13
#define RTSP_METHOD_OPTIONS "OPTIONS"
#define RTSP_METHOD_OPTIONS_LEN 7
#define RTSP_METHOD_PAUSE "PAUSE"
#define RTSP_METHOD_PAUSE_LEN 5
#define RTSP_METHOD_PLAY "PLAY"
#define RTSP_METHOD_PLAY_LEN 4
#define RTSP_METHOD_RECORD "RECORD"
#define RTSP_METHOD_RECORD_LEN 6
#define RTSP_METHOD_SETUP "SETUP"
#define RTSP_METHOD_SETUP_LEN 5
#define RTSP_METHOD_SET_PARAMETER "SET_PARAMETER"
#define RTSP_METHOD_SET_PARAMETER_LEN 13
#define RTSP_METHOD_TEARDOWN "TEARDOWN"
#define RTSP_METHOD_TEARDOWN_LEN 8
#define RTSP_STATUS_CODE "statusCode"
#define RTSP_STATUS_CODE_LEN 10
#define RTSP_STATUS_CODE_REASON "reason"
#define RTSP_STATUS_CODE_REASON_LEN 6
#define RTSP_URL "url"
#define RTSP_URL_LEN 3
#define RTSP_VERSION "version"
#define RTSP_VERSION_LEN 7
#define RTSP_VERSION_1_0 "RTSP/1.0"
#define RTSP_VERSION_1_0_LEN 8
#define SOT_BW_SEND_MESSAGE 6
#define SOT_CS_CONNECT 1
#define SOT_CS_DELETE_FIELD_REQUEST 10
#define SOT_CS_DISCONNECT 2
#define SOT_CS_UPDATE_FIELD 4
#define SOT_CS_UPDATE_FIELD_ACK 5
#define SOT_CS_UPDATE_FIELD_REQUEST 3
#define SOT_SC_CLEAR_DATA 8
#define SOT_SC_DELETE_FIELD 9
#define SOT_SC_INITIAL_DATA 11
#define SOT_SC_STATUS 7
#define SOT_UNKNOWN 0
#define URL_DOCUMENT "document"
#define URL_DOCUMENT_LEN 8
#define URL_HOST "host"
#define URL_HOST_LEN 4
#define URL_PASSWORD "password"
#define URL_PASSWORD_LEN 8
#define URL_PORT "port"
#define URL_PORT_LEN 4
#define URL_USER "user"
#define URL_USER_LEN 4
#define VAR_DATE "date"
#define VAR_DATE_LEN 4
#define VAR_DAY "day"
#define VAR_DAY_LEN 3
#define VAR_ENUM_VALUE_BOOL 3
#define VAR_ENUM_VALUE_BYTEARRAY 20
#define VAR_ENUM_VALUE_DATE 15
#define VAR_ENUM_VALUE_DOUBLE 12
#define VAR_ENUM_VALUE_INT16 5
#define VAR_ENUM_VALUE_INT32 6
#define VAR_ENUM_VALUE_INT64 7
#define VAR_ENUM_VALUE_INT8 4
#define VAR_ENUM_VALUE_MAP 19
#define VAR_ENUM_VALUE_NULL 1
#define VAR_ENUM_VALUE_NUMERIC 13
#define VAR_ENUM_VALUE_STRING 17
#define VAR_ENUM_VALUE_TIME 16
#define VAR_ENUM_VALUE_TIMESTAMP 14
#define VAR_ENUM_VALUE_TYPED_MAP 18
#define VAR_ENUM_VALUE_UINT16 9
#define VAR_ENUM_VALUE_UINT32 10
#define VAR_ENUM_VALUE_UINT64 11
#define VAR_ENUM_VALUE_UINT8 8
#define VAR_ENUM_VALUE_UNDEFINED 2
#define VAR_HOUR "hour"
#define VAR_HOUR_LEN 4
#define VAR_ISDST "isdst"
#define VAR_ISDST_LEN 5
#define VAR_MAP_NAME "__map__name__"
#define VAR_MAP_NAME_LEN 13
#define VAR_MIN "min"
#define VAR_MIN_LEN 3
#define VAR_MONTH "month"
#define VAR_MONTH_LEN 5
#define VAR_NULL_VALUE "__null__value__"
#define VAR_NULL_VALUE_LEN 15
#define VAR_SEC "sec"
#define VAR_SEC_LEN 3
#define VAR_TIME "time"
#define VAR_TIME_LEN 4
#define VAR_TIMESTAMP "timestamp"
#define VAR_TIMESTAMP_LEN 9
#define VAR_TYPE "type"
#define VAR_TYPE_LEN 4
#define VAR_YEAR "year"
#define VAR_YEAR_LEN 4
#define _DEBUG_ 4
#define _ERROR_ 1
#define _FATAL_ 0
#define _FINEST_ 6
#define _FINE_ 5
#define _INFO_ 3
#define _WARNING_ 2
#endif /*DEFINES_H_*/
| 36,383
|
C++
|
.h
| 852
| 41.701878
| 98
| 0.827188
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,526
|
iobuffer.h
|
shiretu_crtmpserver/sources/common/include/utils/buffering/iobuffer.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _IOBUFFER_H
#define _IOBUFFER_H
#include "platform/platform.h"
#include "utils/misc/file.h"
#include "utils/misc/mmapfile.h"
#include "utils/misc/crypto.h"
#define GETAVAILABLEBYTESCOUNT(x) ((x)._published - (x)._consumed)
#define GETIBPOINTER(x) ((uint8_t *)((x)._pBuffer + (x)._consumed))
#define SETIBSENDLIMIT(x,y) \
{ \
if(((x)._sendLimit!=0)&&((x)._sendLimit!=0xffffffff)){ \
ASSERT("Setting a IOBufer send limit over an existing limit"); \
} \
(x)._sendLimit=(y); \
}
#define GETIBSENDLIMIT(x) ((x)._sendLimit)
/*!
@class IOBuffer
@brief Base class which contains all the necessary functions involving input/output buffering.
*/
class DLLEXP IOBuffer {
public:
uint8_t *_pBuffer;
uint32_t _size;
uint32_t _published;
uint32_t _consumed;
uint32_t _minChunkSize;
socklen_t _dummy;
uint32_t _sendLimit;
public:
//constructor/destructor and initialization
IOBuffer();
virtual ~IOBuffer();
/*!
@brief initializes the buffer
@param expected - The expected size of this buffer
*/
void Initialize(uint32_t expected);
/*!
@brief Read from TCP File Descriptor and saves it. This function is advisable for connection-oriented sockets.
@param fd - Descriptor that contains the data
@param expected - Expected size of the receiving buffer
@param recvAmount - Size of data received
*/
bool ReadFromTCPFd(int32_t fd, uint32_t expected, int32_t &recvAmount, int &err);
/*!
@brief Read from UDP File Descriptor and saves it. This function is advisable for connectionless-oriented sockets.
@param fd - Descriptor that contains the data
@param recvAmount - Size of data received
@param peerAddress - The source's address
*/
bool ReadFromUDPFd(int32_t fd, int32_t &recvAmount, sockaddr_in &peerAddress);
/*!
@brief Read from Standard IO and saves it.
@param fd - Descriptor that contains the data
@param expected - Expected size of the receiving buffer
@param recvAmount - Size of data received
*/
bool ReadFromStdio(int32_t fd, uint32_t expected, int32_t &recvAmount);
/*!
@brief Read from File Stream and saves it
@param fs - Descriptor that contains the data
@param size - Size of the receiving buffer
*/
bool ReadFromFs(File &file, uint32_t size);
#ifdef HAS_MMAP
bool ReadFromFs(MmapFile &file, uint32_t size);
#endif /* HAS_MMAP */
/*!
@brief Read data from buffer and copy it.
@param pBuffer - Buffer that contains the data to be read.
@param size - Size of data to read.
*/
bool ReadFromBuffer(const uint8_t *pBuffer, const uint32_t size);
/*!
@brief Read data from an input buffer starting at a designated point
@param pInputBuffer - Pointer to the input buffer
@param start - The point where copying starts
@param size - Size of data to read
*/
void ReadFromInputBuffer(IOBuffer *pInputBuffer, uint32_t start, uint32_t size);
/*!
@brief Read data from an input buffer
@param buffer - Buffer that contains the data to be read.
@param size - Size of data to read.
*/
bool ReadFromInputBuffer(const IOBuffer &buffer, uint32_t size);
/*!
@brief read data from input buffer and also removes it. If the conditions are right,
this can be actually reduced to a simple exchange of internal buffers which is the
fastest way
*/
bool ReadFromInputBufferWithIgnore(IOBuffer &src);
/*!
@brief Read data from buffer from a string
@param binary - The string that will be read
*/
bool ReadFromString(string binary);
/*!
@brief Read data from buffer byte data
@param byte
*/
void ReadFromByte(uint8_t byte);
/*!
@brief Read data from a memory BIO
@param pBIO
*/
bool ReadFromBIO(BIO *pBIO);
/*!
@brief
*/
void ReadFromRepeat(uint8_t byte, uint32_t size);
//Read from this buffer and put to a destination
/*!
@brief Read data from buffer and store it.
@param fd
@param size - Size of buffer
@param sentAmount - Size of data sent
*/
bool WriteToTCPFd(int32_t fd, uint32_t size, int32_t &sentAmount, int &err);
/*!
@brief Read data from standard IO and store it.
@param fd
@param size
*/
bool WriteToStdio(int32_t fd, uint32_t size, int32_t &sentAmount);
//Utility functions
/*!
@brief Returns the minimum chunk size. This value is initialized in the constructor.
*/
uint32_t GetMinChunkSize();
/*!
@brief Sets the value of the minimum chunk size
@param minChunkSize
*/
void SetMinChunkSize(uint32_t minChunkSize);
/*!
@brief Returns the size of the buffer that has already been written on.
*/
uint32_t GetCurrentWritePosition();
/*!
@brief Returns the pointer to the buffer
*/
uint8_t *GetPointer();
//memory management
/*!
@brief Ignores a specified size of data in the buffer
@param size
*/
bool Ignore(uint32_t size);
/*!
@brief Ignores all data in the buffer
*/
bool IgnoreAll();
/*!
@brief Moves the data in a buffer to optimize memory space
*/
bool MoveData();
/*!
@brief Makes sure that there is enough memory space in the buffer. If space is not enough, a new buffer is created.
@param expected - This function makes sure that the size indicated by this parameter is accommodated.
@discussion In the case that a new buffer is created and the current buffer has data, the data is copied to the new buffer.
*/
bool EnsureSize(uint32_t expected);
/*!
@brief
*/
static string DumpBuffer(const uint8_t *pBuffer, uint32_t length);
static string DumpBuffer(MSGHDR &message, uint32_t limit = 0);
string ToString(uint32_t startIndex = 0, uint32_t limit = 0);
operator string();
static void ReleaseDoublePointer(char ***pppPointer);
protected:
void Cleanup();
void Recycle();
};
#endif //_IOBUFFER_H
| 6,435
|
C++
|
.h
| 195
| 30.528205
| 125
| 0.73808
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,527
|
crypto.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/crypto.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CRYPTO_H
#define _CRYPTO_H
#include "platform/platform.h"
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/rc4.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/hmac.h>
#include <openssl/aes.h>
#include <openssl/engine.h>
#include <openssl/conf.h>
/*!
@class DHWrapper
@brief Class that handles the DH wrapper
*/
class DLLEXP DHWrapper {
private:
int32_t _bitsCount;
DH *_pDH;
uint8_t *_pSharedKey;
int32_t _sharedKeyLength;
BIGNUM *_peerPublickey;
public:
DHWrapper(int32_t bitsCount);
virtual ~DHWrapper();
/*!
@brief Initializes the DH wrapper
*/
bool Initialize();
/*!
@brief Copies the public key.
@param pDst - Where the copied key is stored
@param dstLength
*/
bool CopyPublicKey(uint8_t *pDst, int32_t dstLength);
/*!
@brief Copies the private key.
@param pDst - Where the copied key is stored
@param dstLength
*/
bool CopyPrivateKey(uint8_t *pDst, int32_t dstLength);
/*!
@brief Creates a shared secret key
@param pPeerPublicKey
@param length
*/
bool CreateSharedKey(uint8_t *pPeerPublicKey, int32_t length);
/*!
@brief Copies the shared secret key.
@param pDst - Where the copied key is stored
@param dstLength
*/
bool CopySharedKey(uint8_t *pDst, int32_t dstLength);
private:
void Cleanup();
bool CopyKey(BIGNUM *pNum, uint8_t *pDst, int32_t dstLength);
};
DLLEXP void InitRC4Encryption(uint8_t *secretKey, uint8_t *pubKeyIn, uint8_t *pubKeyOut,
RC4_KEY *rc4keyIn, RC4_KEY *rc4keyOut);
DLLEXP string md5(string source, bool textResult);
DLLEXP string md5(uint8_t *pBuffer, uint32_t length, bool textResult);
DLLEXP void HMACsha256(const void *pData, uint32_t dataLength, const void *pKey,
uint32_t keyLength, void *pResult);
DLLEXP string sha256(string source);
DLLEXP string b64(string source);
DLLEXP string b64(uint8_t *pBuffer, uint32_t length);
DLLEXP string unb64(string source);
DLLEXP string unb64(uint8_t *pBuffer, uint32_t length);
DLLEXP string hex(string source);
DLLEXP string hex(const uint8_t *pBuffer, uint32_t length);
DLLEXP string bits(string source);
DLLEXP string bits(const uint8_t *pBuffer, uint32_t length);
DLLEXP string unhex(string source);
DLLEXP string unhex(const uint8_t *pBuffer, uint32_t length);
DLLEXP void CleanupSSL();
#endif /* _CRYPTO_H */
| 3,135
|
C++
|
.h
| 97
| 30.381443
| 88
| 0.755783
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,529
|
linkedlist.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/linkedlist.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
#include <stdlib.h>
template<typename T>
struct LinkedListNode {
LinkedListNode<T> *pPrev;
LinkedListNode<T> *pNext;
T info;
};
template<typename T>
LinkedListNode<T> *AddLinkedList(LinkedListNode<T> *pTo, T info, bool after) {
LinkedListNode<T> *pResult = new LinkedListNode<T>;
pResult->pNext = NULL;
pResult->pPrev = NULL;
pResult->info = info;
if (pTo != NULL) {
if (after) {
if (pTo->pNext != NULL) {
pTo->pNext->pPrev = pResult;
pResult->pNext = pTo->pNext;
pTo->pNext = pResult;
pResult->pPrev = pTo;
} else {
pTo->pNext = pResult;
pResult->pPrev = pTo;
}
} else {
if (pTo->pPrev != NULL) {
pTo->pPrev->pNext = pResult;
pResult->pPrev = pTo->pPrev;
pTo->pPrev = pResult;
pResult->pNext = pTo;
} else {
pTo->pPrev = pResult;
pResult->pNext = pTo;
}
}
}
return pResult;
}
template<typename T>
LinkedListNode<T> *FirstLinkedList(LinkedListNode<T> *pNode) {
while (pNode != NULL) {
if (pNode->pPrev == NULL)
return pNode;
pNode = pNode->pPrev;
}
return NULL;
}
template<typename T>
LinkedListNode<T> *LastLinkedList(LinkedListNode<T> *pNode) {
while (pNode != NULL) {
if (pNode->pNext == NULL)
return pNode;
pNode = pNode->pNext;
}
return NULL;
}
template<typename T>
LinkedListNode<T> *RemoveLinkedList(LinkedListNode<T> *pNode) {
LinkedListNode<T> *pPrev = pNode->pPrev;
LinkedListNode<T> *pNext = pNode->pNext;
if (pPrev != NULL)
pPrev->pNext = pNext;
if (pNext != NULL)
pNext->pPrev = pPrev;
delete pNode;
if (pPrev != NULL)
return pPrev;
return pNext;
}
template<typename T>
class LinkedList {
private:
LinkedListNode<T> *_pHead;
LinkedListNode<T> *_pCurrent;
LinkedListNode<T> *_pTail;
uint32_t _size;
public:
LinkedList() {
_pHead = NULL;
_pCurrent = NULL;
_pTail = NULL;
_size = 0;
}
virtual ~LinkedList() {
LinkedListNode<T> *pTemp = _pTail;
while (pTemp != NULL)
pTemp = RemoveLinkedList<T>(pTemp);
_pHead = NULL;
_pCurrent = NULL;
_pTail = NULL;
_size = 0;
}
LinkedListNode<T> *Head() {
return _pHead;
}
LinkedListNode<T> *Current() {
return _pCurrent;
}
LinkedListNode<T> *Tail() {
return _pTail;
}
uint32_t Size() {
return _size;
}
LinkedListNode<T> *PushHead(T info) {
_pHead = AddLinkedList(_pHead, info, false);
_size++;
if (_pCurrent == NULL)
_pCurrent = _pHead;
if (_pTail == NULL)
_pTail = _pHead;
return _pHead;
}
LinkedListNode<T> *PushCurrent(T info, bool after) {
if (_pHead == NULL)
return PushHead(info);
_pCurrent = AddLinkedList(_pCurrent, info, after);
_size++;
_pHead = FirstLinkedList(_pHead);
_pTail = LastLinkedList(_pTail);
return _pCurrent;
}
LinkedListNode<T> *PushTail(T info) {
if (_pHead == NULL)
return PushHead(info);
_size++;
return (_pTail = AddLinkedList(_pTail, info, true));
}
LinkedListNode<T> *Next() {
return (_pCurrent != NULL && _pCurrent->pNext != NULL) ? (_pCurrent = _pCurrent->pNext) : NULL;
}
LinkedListNode<T> *Prev() {
return (_pCurrent != NULL && _pCurrent->pPrev != NULL) ? (_pCurrent = _pCurrent->pPrev) : NULL;
}
LinkedListNode<T> *Begin() {
return _pCurrent = _pHead;
}
LinkedListNode<T> *End() {
return _pCurrent = _pTail;
}
LinkedListNode<T> *Remove() {
if (_pCurrent == NULL)
return NULL;
_pCurrent = RemoveLinkedList(_pCurrent);
_pHead = FirstLinkedList(_pCurrent);
_pTail = LastLinkedList(_pCurrent);
_size--;
return _pCurrent;
}
};
#endif /* _LINKEDLIST_H */
| 4,318
|
C++
|
.h
| 171
| 22.567251
| 97
| 0.682293
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,531
|
misc.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/misc.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MISC_H
#define _MISC_H
#include "utils/misc/crypto.h"
#include "utils/misc/file.h"
#include "utils/misc/linkedlist.h"
#include "utils/misc/mmapfile.h"
#include "utils/misc/timersmanager.h"
#include "utils/misc/variant.h"
#include "utils/misc/uri.h"
#include "utils/misc/format.h"
#endif /* _MISC_H */
| 1,086
|
C++
|
.h
| 29
| 35.758621
| 72
| 0.747628
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,532
|
format.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/format.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _FORMAT_H
#define _FORMAT_H
#include "platform/platform.h"
DLLEXP string format(const char *pFormat, ...);
DLLEXP string vFormat(const char *pFormat, va_list args);
#endif /* _FORMAT_H */
| 973
|
C++
|
.h
| 24
| 38.666667
| 72
| 0.744974
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,533
|
uri.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/uri.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _URI_H
#define _URI_H
#include "platform/platform.h"
#include "utils/misc/variant.h"
class DLLEXP URI
: public Variant {
private:
//static Variant _dummy;
public:
VARIANT_GETSET(string, originalUri, "");
VARIANT_GETSET(string, fullUri, "");
VARIANT_GETSET(string, fullUriWithAuth, "");
VARIANT_GETSET(string, scheme, "");
VARIANT_GETSET(string, userName, "");
VARIANT_GETSET(string, password, "");
VARIANT_GETSET(string, host, "");
VARIANT_GETSET(string, ip, "");
VARIANT_GETSET(uint16_t, port, 0);
VARIANT_GETSET(bool, portSpecified, false);
VARIANT_GETSET(string, fullDocumentPathWithParameters, "");
VARIANT_GETSET(string, fullDocumentPath, "");
VARIANT_GETSET(string, fullParameters, "");
VARIANT_GETSET(string, documentPath, "");
VARIANT_GETSET(string, document, "");
VARIANT_GETSET(string, documentWithFullParameters, "");
VARIANT_GETSET(Variant, parameters, Variant());
string baseURI();
string derivedURI(string relativePath, bool includeParams);
static bool FromVariant(Variant & variant, URI &uri);
static bool FromString(string stringUri, bool resolveHost, URI &uri);
};
#endif /* _URI_H */
| 1,967
|
C++
|
.h
| 50
| 36.32
| 73
| 0.729134
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,534
|
timersmanager.h
|
shiretu_crtmpserver/sources/common/include/utils/misc/timersmanager.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TIMERSMANAGER_H
#define _TIMERSMANAGER_H
#include "platform/platform.h"
struct TimerEvent {
uint32_t period;
uint64_t triggerTime;
uint32_t id;
void *pUserData;
operator string();
};
typedef bool (*ProcessTimerEvent)(TimerEvent &event);
class DLLEXP TimersManager {
private:
ProcessTimerEvent _processTimerEvent;
map<uint64_t, map<uint32_t, TimerEvent *> > _timers;
uint64_t _lastTime;
uint64_t _currentTime;
bool _processResult;
bool _processing;
public:
TimersManager(ProcessTimerEvent processTimerEvent);
virtual ~TimersManager();
void AddTimer(TimerEvent &timerEvent);
void RemoveTimer(uint32_t eventTimerId);
int32_t TimeElapsed();
private:
string DumpTimers();
};
#endif /* _TIMERSMANAGER_H */
| 1,508
|
C++
|
.h
| 47
| 30.170213
| 72
| 0.768595
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,538
|
baseloglocation.h
|
shiretu_crtmpserver/sources/common/include/utils/logging/baseloglocation.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BASELOGLOCATION_H_
#define BASELOGLOCATION_H_
#include "platform/platform.h"
#include "utils/misc/variant.h"
/*!
@class BaseLogLocation
@brief Base class that all logging must derive from.
*/
class DLLEXP BaseLogLocation {
protected:
int32_t _level;
string _name;
int32_t _specificLevel;
bool _singleLine;
Variant _configuration;
public:
BaseLogLocation(Variant &configuration);
virtual ~BaseLogLocation();
int32_t GetLevel();
void SetLevel(int32_t level);
string GetName();
void SetName(string name);
virtual bool EvalLogLevel(int32_t level, const char *pFileName, uint32_t lineNumber,
const char *pFunctionName);
virtual bool Init();
virtual void Log(int32_t level, const char *pFileName, uint32_t lineNumber,
const char *pFunctionName, string &message) = 0;
virtual void SignalFork() = 0;
private:
bool EvalLogLevel(int32_t level);
};
#endif /*BASELOGLOCATION_H_*/
| 1,682
|
C++
|
.h
| 50
| 31.64
| 85
| 0.762931
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,540
|
logging.h
|
shiretu_crtmpserver/sources/common/include/utils/logging/logging.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _LOGGING_H
#define _LOGGING_H
#include "defines.h"
#include "utils/logging/baseloglocation.h"
#include "utils/logging/consoleloglocation.h"
#include "utils/logging/fileloglocation.h"
#include "utils/logging/logcatloglocation.h"
#include "utils/logging/logger.h"
#ifdef VALIDATE_FROMAT_SPECIFIERS
#define __VALIDATE_FROMAT_SPECIFIERS(...) \
do { \
char ___tempLocation[1024]; \
snprintf(___tempLocation,1023,__VA_ARGS__); \
}while (0)
#else
#define __VALIDATE_FROMAT_SPECIFIERS(...)
#endif /* VALIDATE_FROMAT_SPECIFIERS */
#ifdef FILE_OVERRIDE
#define __FILE__OVERRIDE ""
#else
#define __FILE__OVERRIDE __FILE__
#endif
#ifdef LINE_OVERRIDE
#define __LINE__OVERRIDE 0
#else
#define __LINE__OVERRIDE __LINE__
#endif
#ifdef FUNC_OVERRIDE
#define __FUNC__OVERRIDE ""
#else
#define __FUNC__OVERRIDE __func__
#endif
#ifdef FILE_OVERRIDE
#define __FILE__OVERRIDE ""
#define E__FILE__ __FILE__OVERRIDE
#else /* FILE_OVERRIDE */
#define __FILE__OVERRIDE __FILE__
#ifdef SHORT_PATH_IN_LOGGER
#define E__FILE__ ((const char *)__FILE__OVERRIDE)+SHORT_PATH_IN_LOGGER
#else /* SHORT_PATH_IN_LOGGER */
#define E__FILE__ __FILE__OVERRIDE
#endif /* SHORT_PATH_IN_LOGGER */
#endif /* FILE_OVERRIDE */
#define LOG(level,...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(level, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define FATAL(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_FATAL_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define WARN(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_WARNING_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define INFO(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_INFO_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define DEBUG(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_DEBUG_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define FINE(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_FINE_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define FINEST(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_FINEST_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);}while(0)
#define ASSERT(...) do{__VALIDATE_FROMAT_SPECIFIERS(__VA_ARGS__);Logger::Log(_FATAL_, E__FILE__, __LINE__OVERRIDE, __FUNC__OVERRIDE, __VA_ARGS__);o_assert(false);abort();}while(0)
#define NYI WARN("%s not yet implemented",__FUNC__OVERRIDE);
#define NYIR do{NYI;return false;}while(0)
#define NYIA do{NYI;o_assert(false);abort();}while(0)
#endif /* _LOGGING_H */
| 3,429
|
C++
|
.h
| 73
| 45.493151
| 179
| 0.698565
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,542
|
platform.h
|
shiretu_crtmpserver/sources/common/include/platform/platform.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PLATFORM_H
#define _PLATFORM_H
#include "platform/endianess/endianness.h"
#ifdef OSX
#include "platform/osx/osxplatform.h"
#define Platform OSXPlatform
#endif /* OSX */
#ifdef LINUX
#include "platform/linux/max.h"
#include "platform/linux/linuxplatform.h"
#define Platform LinuxPlatform
#endif /* LINUX */
#ifdef FREEBSD
#include "platform/freebsd/freebsdplatform.h"
#define Platform FreeBSDPlatform
#endif /* FREEBSD */
#ifdef SOLARIS
#include "platform/solaris/solarisplatform.h"
#define Platform SolarisPlatform
#endif /* SOLARIS */
#ifdef WIN32
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include "platform/windows/max.h"
#include "platform/windows/win32platform.h"
#define Platform Win32Platform
#endif /* WIN32 */
#ifdef ANDROID
#include "platform/android/max.h"
#include "platform/android/androidplatform.h"
#define Platform AndroidPlatform
#endif /* ANDROID */
#ifdef ASSERT_OVERRIDE
#define o_assert(x) \
do { \
if((x)==0) \
exit(-1); \
} while(0)
#else
#define o_assert(x) assert(x)
#endif
#endif /* _PLATFORM_H */
| 1,822
|
C++
|
.h
| 60
| 28.85
| 72
| 0.764135
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,545
|
freebsdplatform.h
|
shiretu_crtmpserver/sources/common/include/platform/freebsd/freebsdplatform.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef FREEBSD
#ifndef _FREEBSDPLATFORM_H
#define _FREEBSDPLATFORM_H
#include "platform/baseplatform.h"
#ifndef PRIz
#define PRIz "z"
#endif /* PRIz */
//platform includes
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <algorithm>
#include <arpa/inet.h>
#include <assert.h>
#include <cctype>
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <list>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <sstream>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <vector>
#include <queue>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
#include <spawn.h>
#include <sys/resource.h>
#include <unistd.h>
using namespace std;
//platform defines
#define DLLEXP
#define HAS_MMAP 1
#define COLOR_TYPE const char *
#define FATAL_COLOR "\033[01;31m"
#define ERROR_COLOR "\033[22;31m"
#define WARNING_COLOR "\033[01;33m"
#define INFO_COLOR "\033[22;36m"
#define DEBUG_COLOR "\033[01;37m"
#define FINE_COLOR "\033[22;37m"
#define FINEST_COLOR "\033[22;37m"
#define NORMAL_COLOR "\033[0m"
#define SET_CONSOLE_TEXT_COLOR(color) fprintf(stdout,"%s",color)
#define READ_FD read
#define WRITE_FD write
#define SOCKET int32_t
#define LASTSOCKETERROR errno
#define SOCKERROR_EINPROGRESS EINPROGRESS
#define SOCKERROR_EAGAIN EAGAIN
#define SOCKERROR_ECONNRESET ECONNRESET
#define SOCKERROR_ENOBUFS ENOBUFS
#define LIB_HANDLER void *
#define FREE_LIBRARY(libHandler) dlclose((libHandler))
#define LOAD_LIBRARY(file,flags) dlopen((file), (flags))
#define LOAD_LIBRARY_FLAGS RTLD_NOW | RTLD_LOCAL
#define OPEN_LIBRARY_ERROR STR(string(dlerror()))
#define GET_PROC_ADDRESS(libHandler, procName) dlsym((libHandler), (procName))
#define LIBRARY_NAME_PATTERN "lib%s.so"
#define PATH_SEPARATOR '/'
#define CLOSE_SOCKET(fd) if((fd)>=0) close((fd))
#define InitNetworking()
#define HAS_KQUEUE_TIMERS
#define KQUEUE_TIMER_MULTIPLIER 1000
#define SET_UNKNOWN 0
#define SET_READ 1
#define SET_WRITE 2
#define SET_TIMER 3
#define FD_READ_CHUNK 32768
#define FD_WRITE_CHUNK FD_READ_CHUNK
#define RESET_TIMER(timer,sec,usec)
#define MAP_NOCACHE 0
#define MAP_NOEXTEND 0
#define NOTE_USECONDS 0
#define SRAND() sranddev();
#define Timestamp struct tm
#define Timestamp_init {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
#define PIOFFT off_t
#define GetPid getpid
#define PutEnv putenv
#define TzSet tzset
#define Chmod chmod
#define CLOCKS_PER_SECOND 1000000L
#define GETCLOCKS(result,type) \
do { \
struct timeval ___timer___; \
gettimeofday(&___timer___,NULL); \
result=(type)___timer___.tv_sec*(type)CLOCKS_PER_SECOND+(type) ___timer___.tv_usec; \
}while(0);
#define GETMILLISECONDS(result) \
do { \
struct timespec ___timer___; \
clock_gettime(CLOCK_MONOTONIC_FAST, &___timer___); \
result=(uint64_t)___timer___.tv_sec*1000+___timer___.tv_nsec/1000000; \
}while(0);
#define GETNTP(result) \
do { \
struct timeval tv; \
gettimeofday(&tv,NULL); \
result=(((uint64_t)tv.tv_sec + 2208988800U)<<32)|((((uint32_t)tv.tv_usec) << 12) + (((uint32_t)tv.tv_usec) << 8) - ((((uint32_t)tv.tv_usec) * 1825) >> 5)); \
}while (0);
#define GETCUSTOMNTP(result,value) \
do { \
struct timeval tv; \
tv.tv_sec=value/CLOCKS_PER_SECOND; \
tv.tv_usec=value-tv.tv_sec*CLOCKS_PER_SECOND; \
result=(((uint64_t)tv.tv_sec + 2208988800U)<<32)|((((uint32_t)tv.tv_usec) << 12) + (((uint32_t)tv.tv_usec) << 8) - ((((uint32_t)tv.tv_usec) * 1825) >> 5)); \
}while (0);
class FreeBSDPlatform
: public BasePlatform {
public:
FreeBSDPlatform();
virtual ~FreeBSDPlatform();
};
typedef void (*SignalFnc)(void);
typedef struct _select_event {
uint8_t type;
} select_event;
#define MSGHDR struct msghdr
#define IOVEC iovec
#define MSGHDR_MSG_IOV msg_iov
#define MSGHDR_MSG_IOVLEN msg_iovlen
#define MSGHDR_MSG_IOVLEN_TYPE int
#define MSGHDR_MSG_NAME msg_name
#define MSGHDR_MSG_NAMELEN msg_namelen
#define IOVEC_IOV_BASE iov_base
#define IOVEC_IOV_LEN iov_len
#define IOVEC_IOV_BASE_TYPE uint8_t
#define SENDMSG(s,msg,flags,sent) sendmsg(s,msg,flags)
#define FILE_OFFSET_BITS 64
#define ftell64 ftello
#define fseek64 fseeko
string GetEnvVariable(const char *pEnvVarName);
void replace(string &target, string search, string replacement);
bool fileExists(string path);
string lowerCase(string value);
string upperCase(string value);
string changeCase(string &value, bool lowerCase);
string tagToString(uint64_t tag);
bool setMaxFdCount(uint32_t ¤t, uint32_t &max);
bool enableCoreDumps();
bool setFdJoinMulticast(SOCKET sock, string bindIp, uint16_t bindPort, string ssmIp);
bool setFdCloseOnExec(int fd);
bool setFdNonBlock(SOCKET fd);
bool setFdNoSIGPIPE(SOCKET fd);
bool setFdKeepAlive(SOCKET fd, bool isUdp);
bool setFdNoNagle(SOCKET fd, bool isUdp);
bool setFdReuseAddress(SOCKET fd);
bool setFdTTL(SOCKET fd, uint8_t ttl);
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl);
bool setFdTOS(SOCKET fd, uint8_t tos);
bool setFdMaxSndRcvBuff(SOCKET fd);
bool setFdOptions(SOCKET fd, bool isUdp);
void killProcess(pid_t pid);
bool deleteFile(string path);
bool deleteFolder(string path, bool force);
bool createFolder(string path, bool recursive);
string getHostByName(string name);
bool isNumeric(string value);
void split(string str, string separator, vector<string> &result);
uint64_t getTagMask(uint64_t tag);
string generateRandomString(uint32_t length);
void lTrim(string &value);
void rTrim(string &value);
void trim(string &value);
int8_t getCPUCount();
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings);
void splitFileName(string fileName, string &name, string &extension, char separator = '.');
double getFileModificationDate(string path);
string normalizePath(string base, string file);
bool listFolder(string path, vector<string> &result,
bool normalizeAllPaths = true, bool includeFolders = false,
bool recursive = true);
bool moveFile(string src, string dst);
bool isAbsolutePath(string &path);
void installSignal(int sig, SignalFnc pSignalFnc);
void installQuitSignal(SignalFnc pQuitSignalFnc);
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc);
#define getutctime() time(NULL)
time_t getlocaltime();
time_t gettimeoffset();
void GetFinishedProcesses(vector<pid_t> &pids, bool &noMorePids);
bool LaunchProcess(string fullBinaryPath, vector<string> &arguments, vector<string> &envVars, pid_t &pid);
#endif /* _FREEBSDPLATFORM_H */
#endif /* FREEBSD */
| 7,420
|
C++
|
.h
| 218
| 32.711009
| 158
| 0.760785
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,546
|
osxplatform.h
|
shiretu_crtmpserver/sources/common/include/platform/osx/osxplatform.h
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef OSX
#ifndef _OSXPLATFORM_H
#define _OSXPLATFORM_H
#include "platform/baseplatform.h"
#ifndef PRIz
#define PRIz "z"
#endif /* PRIz */
//platform includes
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <AvailabilityMacros.h>
#include <algorithm>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <assert.h>
#include <cctype>
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <glob.h>
#include <list>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <sstream>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <vector>
#include <queue>
#include <spawn.h>
using namespace std;
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
//platform defines
#define DLLEXP
#define HAS_MMAP 1
#define COLOR_TYPE const char *
#define FATAL_COLOR "\033[01;31m"
#define ERROR_COLOR "\033[22;31m"
#define WARNING_COLOR "\033[01;33m"
#define INFO_COLOR "\033[22;36m"
#define DEBUG_COLOR "\033[01;37m"
#define FINE_COLOR "\033[22;37m"
#define FINEST_COLOR "\033[22;37m"
#define NORMAL_COLOR "\033[0m"
#define SET_CONSOLE_TEXT_COLOR(color) fprintf(stdout,"%s",color)
#define MSG_NOSIGNAL 0
#define READ_FD read
#define WRITE_FD write
#define SOCKET int32_t
#define LASTSOCKETERROR errno
#define SOCKERROR_EINPROGRESS EINPROGRESS
#define SOCKERROR_EAGAIN EAGAIN
#define SOCKERROR_ECONNRESET ECONNRESET
#define SOCKERROR_ENOBUFS ENOBUFS
#define LIB_HANDLER void *
#define FREE_LIBRARY(libHandler) dlclose((libHandler))
#define LOAD_LIBRARY(file,flags) dlopen((file), (flags))
#define LOAD_LIBRARY_FLAGS RTLD_NOW | RTLD_LOCAL
#define OPEN_LIBRARY_ERROR STR(string(dlerror()))
#define GET_PROC_ADDRESS(libHandler, procName) dlsym((libHandler), (procName))
#define LIBRARY_NAME_PATTERN "lib%s.dylib"
#define PATH_SEPARATOR '/'
#define CLOSE_SOCKET(fd) if((fd)>=0) close((fd))
#define InitNetworking()
#ifdef MAC_OS_X_VERSION_10_6
#define HAS_KQUEUE_TIMERS
#define KQUEUE_TIMER_MULTIPLIER 1000000
#endif /* MAC_OS_X_VERSION_10_6 */
#define SET_UNKNOWN 0
#define SET_READ 1
#define SET_WRITE 2
#define SET_TIMER 3
#define FD_READ_CHUNK 32768
#define FD_WRITE_CHUNK FD_READ_CHUNK
#define RESET_TIMER(timer,sec,usec) timer.tv_sec=sec;timer.tv_usec=usec;
#define SRAND() sranddev();
#define Timestamp struct tm
#define Timestamp_init {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
#define PIOFFT off_t
#define GetPid getpid
#define PutEnv putenv
#define TzSet tzset
#define Chmod chmod
#define CLOCKS_PER_SECOND CLOCKS_PER_SEC
#define GETCLOCKS(result,type) \
do { \
struct timeval ___timer___; \
gettimeofday(&___timer___,NULL); \
result=(type)___timer___.tv_sec*(type)CLOCKS_PER_SECOND+(type) ___timer___.tv_usec; \
}while(0);
#define GETMILLISECONDS(result) \
do { \
struct timeval ___timer___; \
gettimeofday(&___timer___,NULL); \
result=(uint64_t)___timer___.tv_sec*1000+___timer___.tv_usec/1000; \
}while(0);
#define GETNTP(result) \
do { \
struct timeval tv; \
gettimeofday(&tv,NULL); \
result=(((uint64_t)tv.tv_sec + 2208988800U)<<32)|((((uint32_t)tv.tv_usec) << 12) + (((uint32_t)tv.tv_usec) << 8) - ((((uint32_t)tv.tv_usec) * 1825) >> 5)); \
}while (0);
#define GETCUSTOMNTP(result,value) \
do { \
struct timeval tv; \
tv.tv_sec=value/CLOCKS_PER_SECOND; \
tv.tv_usec=value-tv.tv_sec*CLOCKS_PER_SECOND; \
result=(((uint64_t)tv.tv_sec + 2208988800U)<<32)|((((uint32_t)tv.tv_usec) << 12) + (((uint32_t)tv.tv_usec) << 8) - ((((uint32_t)tv.tv_usec) * 1825) >> 5)); \
}while (0);
class OSXPlatform
: public BasePlatform {
public:
OSXPlatform();
virtual ~OSXPlatform();
};
typedef void (*SignalFnc)(void);
typedef struct _select_event {
uint8_t type;
} select_event;
#define MSGHDR struct msghdr
#define IOVEC iovec
#define MSGHDR_MSG_IOV msg_iov
#define MSGHDR_MSG_IOVLEN msg_iovlen
#define MSGHDR_MSG_IOVLEN_TYPE int
#define MSGHDR_MSG_NAME msg_name
#define MSGHDR_MSG_NAMELEN msg_namelen
#define IOVEC_IOV_BASE iov_base
#define IOVEC_IOV_LEN iov_len
#define IOVEC_IOV_BASE_TYPE uint8_t
#define SENDMSG(s,msg,flags,sent) sendmsg(s,msg,flags)
#define ftell64 ftello
#define fseek64 fseeko
string GetEnvVariable(const char *pEnvVarName);
void replace(string &target, string search, string replacement);
bool fileExists(string path);
string lowerCase(string value);
string upperCase(string value);
string changeCase(string &value, bool lowerCase);
string tagToString(uint64_t tag);
bool setMaxFdCount(uint32_t ¤t, uint32_t &max);
bool enableCoreDumps();
bool setFdJoinMulticast(SOCKET sock, string bindIp, uint16_t bindPort, string ssmIp);
bool setFdCloseOnExec(int fd);
bool setFdNonBlock(SOCKET fd);
bool setFdNoSIGPIPE(SOCKET fd);
bool setFdKeepAlive(SOCKET fd, bool isUdp);
bool setFdNoNagle(SOCKET fd, bool isUdp);
bool setFdReuseAddress(SOCKET fd);
bool setFdTTL(SOCKET fd, uint8_t ttl);
bool setFdMulticastTTL(SOCKET fd, uint8_t ttl);
bool setFdTOS(SOCKET fd, uint8_t tos);
bool setFdMaxSndRcvBuff(SOCKET fd);
bool setFdOptions(SOCKET fd, bool isUdp);
void killProcess(pid_t pid);
bool deleteFile(string path);
bool deleteFolder(string path, bool force);
bool createFolder(string path, bool recursive);
string getHostByName(string name);
bool isNumeric(string value);
void split(string str, string separator, vector<string> &result);
uint64_t getTagMask(uint64_t tag);
string generateRandomString(uint32_t length);
void lTrim(string &value);
void rTrim(string &value);
void trim(string &value);
int8_t getCPUCount();
map<string, string> mapping(string str, string separator1, string separator2, bool trimStrings);
void splitFileName(string fileName, string &name, string &extension, char separator = '.');
double getFileModificationDate(string path);
string normalizePath(string base, string file);
bool listFolder(string path, vector<string> &result,
bool normalizeAllPaths = true, bool includeFolders = false,
bool recursive = true);
bool moveFile(string src, string dst);
bool isAbsolutePath(string &path);
void installSignal(int sig, SignalFnc pSignalFnc);
void installQuitSignal(SignalFnc pQuitSignalFnc);
void installConfRereadSignal(SignalFnc pConfRereadSignalFnc);
#define getutctime() time(NULL)
time_t getlocaltime();
time_t gettimeoffset();
void GetFinishedProcesses(vector<pid_t> &pids, bool &noMorePids);
bool LaunchProcess(string fullBinaryPath, vector<string> &arguments, vector<string> &envVars, pid_t &pid);
#endif /* _OSXPLATFORM_H */
#endif /* OSX */
| 7,389
|
C++
|
.h
| 213
| 33.356808
| 158
| 0.760475
|
shiretu/crtmpserver
| 134
| 66
| 8
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
750,550
|
MainApp.cpp
|
anonbeat_guayadeque/src/MainApp.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "MainApp.h"
#include "Config.h"
#include "Curl.h"
#include "Images.h"
#include "MainFrame.h"
#include "mpris.h"
#include "SplashWin.h"
#include "Settings.h"
#include "Utils.h"
#include "wx/clipbrd.h"
#include <wx/image.h>
#include <wx/tooltip.h>
#include <wx/stdpaths.h>
#include <wx/utils.h>
#include <wx/debugrpt.h>
IMPLEMENT_APP( Guayadeque::guMainApp );
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guMainApp::guMainApp() : wxApp()
{
// m_Db = NULL;
m_DbCache = NULL;
m_SingleInstanceChecker = NULL;
#if wxUSE_ON_FATAL_EXCEPTION // Thanks TheBigRed
wxHandleFatalExceptions();
#endif
if( !wxDirExists( guPATH_CONFIG ) )
{
wxMkdir( guPATH_CONFIG, 0770 );
guLogMessage( wxT( "Created the configuration folder" ) );
}
if( !wxDirExists( guPATH_LYRICS ) )
{
wxMkdir( guPATH_LYRICS, 0770 );
guLogMessage( wxT( "Created the lyrics folder" ) );
}
if( !wxDirExists( guPATH_COLLECTIONS ) )
{
wxMkdir( guPATH_COLLECTIONS, 0770 );
guLogMessage( wxT( "Created the collections folder" ) );
}
if( !wxDirExists( guPATH_RADIOS ) )
{
wxMkdir( guPATH_RADIOS, 0770 );
guLogMessage( wxT( "Created the Radios folder" ) );
}
if( !wxDirExists( guPATH_JAMENDO ) )
{
wxMkdir( guPATH_JAMENDO, 0770 );
wxMkdir( guPATH_JAMENDO_COVERS, 0770 );
guLogMessage( wxT( "Created the Jamendo folder" ) );
}
if( !wxDirExists( guPATH_MAGNATUNE ) )
{
wxMkdir( guPATH_MAGNATUNE, 0770 );
wxMkdir( guPATH_MAGNATUNE_COVERS, 0770 );
guLogMessage( wxT( "Created the Magnatune folder" ) );
}
if( !wxDirExists( guPATH_PODCASTS ) )
{
wxMkdir( guPATH_PODCASTS, 0770 );
guLogMessage( wxT( "Created the Podcasts folder" ) );
}
if( !wxDirExists( guPATH_DEVICES ) )
{
wxMkdir( guPATH_DEVICES, 0770 );
guLogMessage( wxT( "Created the Devices folder" ) );
}
if( !wxDirExists( guPATH_LAYOUTS ) )
{
wxMkdir( guPATH_LAYOUTS, 0770 );
guLogMessage( wxT( "Created the Layouts folder" ) );
}
if( !wxFileExists( guPATH_CONFIG_FILENAME ) )
{
if( wxFileExists( wxT( DATADIR "/guayadeque.default.conf" ) ) )
{
wxCopyFile( wxT( DATADIR "/guayadeque.default.conf" ),
guPATH_CONFIG_FILENAME, false );
}
else if( wxFileExists( wxT( "/usr/local/share/guayadeque/guayadeque.default.conf" ) ) )
{
wxCopyFile( wxT( "/usr/local/share/guayadeque/guayadeque.default.conf" ),
guPATH_CONFIG_FILENAME, false );
}
guLogMessage( wxT( "Created the default configuration file" ) );
}
if( !wxFileExists( guPATH_EQUALIZERS_FILENAME ) )
{
if( wxFileExists( wxT( DATADIR "/equalizers.default.conf" ) ) )
{
wxCopyFile( wxT( DATADIR "/equalizers.default.conf" ),
guPATH_EQUALIZERS_FILENAME, false );
}
else if( wxFileExists( wxT( "/usr/local/share/guayadeque/equalizers.default.conf" ) ) )
{
wxCopyFile( wxT( "/usr/local/share/guayadeque/equalizers.default.conf" ),
guPATH_EQUALIZERS_FILENAME, false );
}
guLogMessage( wxT( "Created the default equalizers file" ) );
}
if( !wxFileExists( guPATH_LYRICS_SOURCES_FILENAME ) )
{
if( wxFileExists( wxT( DATADIR "/lyrics_sources.xml" ) ) )
{
wxCopyFile( wxT( DATADIR "/lyrics_sources.xml" ),
guPATH_LYRICS_SOURCES_FILENAME, false );
}
else if( wxFileExists( wxT( "/usr/local/share/guayadeque/lyrics_sources.xml" ) ) )
{
wxCopyFile( wxT( "/usr/local/share/guayadeque/lyrics_sources.xml" ),
guPATH_LYRICS_SOURCES_FILENAME, false );
}
guLogMessage( wxT( "Created the default lyrics sources file" ) );
}
m_Config = new guConfig();
m_Config->Set( m_Config );
}
// -------------------------------------------------------------------------------- //
guMainApp::~guMainApp()
{
if( m_SingleInstanceChecker )
delete m_SingleInstanceChecker;
if( m_DbCache )
{
m_DbCache->Close();
delete m_DbCache;
}
// config
if( m_Config )
delete m_Config;
}
// -------------------------------------------------------------------------------- //
// Its done this way to avoid the warning of temporary address
void inline Append_String( DBusMessageIter * iter, const char * str )
{
dbus_message_iter_append_basic( iter, DBUS_TYPE_STRING, &str );
}
// -------------------------------------------------------------------------------- //
bool SendFilesByMPRIS( const int argc, wxChar * argv[] )
{
DBusError dberr;
DBusConnection * dbconn;
DBusMessage * dbmsg, * dbreply;
DBusMessageIter dbiter;
DBusMessageIter dbitertracks;
dbus_error_init( &dberr );
dbconn = dbus_bus_get( DBUS_BUS_SESSION, &dberr );
if( dbus_error_is_set( &dberr ) )
{
printf( "getting session bus failed: %s\n", dberr.message );
dbus_error_free( &dberr );
return false;
}
dbmsg = dbus_message_new_method_call( GUAYADEQUE_MPRIS_SERVICENAME,
GUAYADEQUE_MPRIS_TRACKLIST_PATH,
GUAYADEQUE_MPRIS_INTERFACE,
"AddTracks" );
if( dbmsg == NULL )
{
guLogError( wxT( "Couldn’t create a DBusMessage" ) );
return false;
}
dbus_message_iter_init_append( dbmsg, &dbiter );
dbus_message_iter_open_container( &dbiter, DBUS_TYPE_ARRAY, "s", &dbitertracks );
wxString FilePath;
for( int index = 1; index < argc; index++ )
{
FilePath = argv[ index ];
//guLogMessage( wxT( "Trying to add file '%s'" ), argv[ index ] );
Append_String( &dbitertracks, FilePath.char_str() );
}
dbus_message_iter_close_container( &dbiter, &dbitertracks );
dbus_bool_t PlayTrack = false;
dbus_message_iter_append_basic( &dbiter, DBUS_TYPE_BOOLEAN, &PlayTrack );
dbreply = dbus_connection_send_with_reply_and_block( dbconn, dbmsg, 5000, &dberr );
if( dbus_error_is_set( &dberr ) )
{
guLogMessage( wxT( "Error adding files: '%s'" ), wxString( dberr.message, wxConvUTF8 ).c_str() );
dbus_message_unref( dbmsg );
dbus_error_free( &dberr );
return false;
}
if( dbreply )
dbus_message_unref( dbreply );
/* Don’t need this anymore */
dbus_message_unref( dbmsg );
dbus_connection_unref( dbconn );
return true;
}
// -------------------------------------------------------------------------------- //
bool MakeWindowVisible( void )
{
DBusError dberr;
DBusConnection * dbconn;
DBusMessage * dbmsg, * dbreply;
dbus_error_init( &dberr );
dbconn = dbus_bus_get( DBUS_BUS_SESSION, &dberr );
if( dbus_error_is_set( &dberr ) )
{
printf( "getting session bus failed: %s\n", dberr.message );
dbus_error_free( &dberr );
return false;
}
dbmsg = dbus_message_new_method_call( "org.mpris.MediaPlayer2.guayadeque",
"/org/mpris/MediaPlayer2",
"org.mpris.MediaPlayer2",
"Raise" );
if( dbmsg == NULL )
{
guLogError( wxT( "Couldn’t create a DBusMessage" ) );
return false;
}
dbreply = dbus_connection_send_with_reply_and_block( dbconn, dbmsg, 5000, &dberr );
if( dbus_error_is_set( &dberr ) )
{
guLogMessage( wxT( "Error showing window" ) );
dbus_message_unref( dbmsg );
dbus_error_free( &dberr );
return false;
}
if( dbreply )
dbus_message_unref( dbreply );
/* Don’t need this anymore */
dbus_message_unref( dbmsg );
dbus_connection_unref( dbconn );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMainApp::OnInit()
{
guRandomInit();
wxLog::SetActiveTarget( new wxLogStderr( stdout ) );
// Init all image handlers
wxInitAllImageHandlers();
const wxString AppName = wxString::Format( wxT( ".guayadeque/.guayadeque-%s" ), wxGetUserId().c_str() );
//guLogMessage( wxT( "Init: %s" ), AppName.c_str() );
while( true )
{
if( m_SingleInstanceChecker )
delete m_SingleInstanceChecker;
m_SingleInstanceChecker = new wxSingleInstanceChecker( AppName );
if( m_SingleInstanceChecker->IsAnotherRunning() )
{
int RetryCnt = 0;
if( argc > 1 )
{
while( RetryCnt++ < 25 )
{
if( SendFilesByMPRIS( argc, argv ) )
{
break;
}
wxMilliSleep( 100 );
}
}
if( ( RetryCnt < 25 ) && MakeWindowVisible() )
return false;
//guLogMessage( wxT( "Another program instance is already running, aborting." ) );
if( wxMessageBox( _( "Another program instance is already running." ) + "\n" + _( "Do you want to continue with the program?" ),
_( "Confirm" ),
wxICON_QUESTION | wxYES_NO ) == wxYES )
{
if( !wxRemoveFile( wxGetHomeDir() + "/" + AppName ) )
{
guLogMessage( wxT( "Could not delete the file: %s" ), AppName.c_str() );
}
wxMilliSleep( 1000 );
}
else
{
delete m_SingleInstanceChecker;
return false;
}
}
else
{
break;
}
}
// If enabled Show the Splash Screen on Startup
if( m_Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_SPLASH_SCREEN, true, CONFIG_PATH_GENERAL ) )
{
guSplashFrame * SplashFrame = new guSplashFrame( 0 );
if( !SplashFrame )
guLogError( wxT( "Could not create splash object" ) );
SplashFrame->Show( true );
wxYield();
//wxMilliSleep( 300 );
}
// Use the primary clipboard which is shared with other applications
wxTheClipboard->UsePrimarySelection( false );
// Init the Curl Library
guCurl::CurlInit();
int LangId = m_Config->ReadNum( CONFIG_KEY_GENERAL_LANGUAGE, wxLANGUAGE_DEFAULT, CONFIG_PATH_GENERAL );
if( m_Locale.Init( LangId ) )
{
m_Locale.AddCatalogLookupPathPrefix( wxT( "/usr/share/locale" ) );
m_Locale.AddCatalog( wxT( "guayadeque" ) );
guLogMessage( wxT( "Initialized locale ( %s )" ), m_Locale.GetName().c_str() );
}
else
{
const wxLanguageInfo * LangInfo = wxLocale::GetLanguageInfo( LangId );
if( LangInfo )
{
guLogError( wxT( "Could not initialize the translations engine for ( %s )" ), LangInfo->CanonicalName.c_str() );
guLogError( wxT( "Locale directory '%s'" ), wxStandardPaths::Get().GetLocalizedResourcesDir( LangInfo->CanonicalName, wxStandardPaths::ResourceCat_Messages).c_str() );
}
else
{
guLogError( wxT( "Could not initialize the translations engine for (%d)" ), LangId );
}
}
// Enable tooltips
wxToolTip::Enable( true );
m_DbCache = new guDbCache( guPATH_DBCACHE );
if( !m_DbCache )
{
guLogError( wxT( "Could not open the guayadeque cache database" ) );
}
m_DbCache->SetDbCache();
// Initialize the MainFrame object
guMainFrame * Frame = new guMainFrame( 0, m_DbCache );
SetTopWindow( Frame );
//Frame->SetMainFrame();
wxIcon MainIcon;
MainIcon.CopyFromBitmap( guImage( guIMAGE_INDEX_guayadeque ) );
Frame->SetIcon( MainIcon );
// If Minimize is enabled minimized or hide it if Taskbar Icon is enabled
if( m_Config->ReadBool( CONFIG_KEY_GENERAL_START_MINIMIZED, false, CONFIG_PATH_GENERAL ) )
{
if( m_Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_TASK_BAR_ICON, false, CONFIG_PATH_GENERAL ) &&
m_Config->ReadBool( CONFIG_KEY_GENERAL_CLOSE_TO_TASKBAR, false, CONFIG_PATH_GENERAL ) )
{
Frame->Show( false );
//Frame->Hide();
}
else
{
Frame->Show();
Frame->Iconize( true );
}
}
else
{
Frame->Show();
}
return true;
}
// -------------------------------------------------------------------------------- //
int guMainApp::OnExit()
{
// Free any resources used by Curl Library
guCurl::CurlDone();
return 0;
}
// -------------------------------------------------------------------------------- //
void guMainApp::OnFatalException()
{
wxDebugReport Report;
wxDebugReportPreviewStd Preview;
Report.AddAll();
if( Preview.Show( Report ) )
Report.Process();
}
}
// -------------------------------------------------------------------------------- //
| 14,371
|
C++
|
.cpp
| 389
| 29.22365
| 179
| 0.553029
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,551
|
DbRadios.cpp
|
anonbeat_guayadeque/src/db/DbRadios.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "DbRadios.h"
#include "Config.h"
#include <wx/arrimpl.cpp>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guRadioStations )
// -------------------------------------------------------------------------------- //
guDbRadios::guDbRadios( const wxString &dbname ) : guDb( dbname )
{
wxArrayString query;
query.Add( wxT( "CREATE TABLE IF NOT EXISTS radiogenres( radiogenre_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"radiogenre_name VARCHAR COLLATE NOCASE, radiogenre_source INTEGER, radiogenre_flags INTEGER );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'radiogenre_id' on radiogenres (radiogenre_id ASC);" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 1, '60s', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 2, '80s', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 3, '90s', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 4, 'Alternative', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 5, 'Ambient', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 6, 'Blues', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 7, 'Chill', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 8, 'Classical', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 9, 'Country', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 10, 'Dance', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 11, 'Downtempo', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 12, 'Easy Listening', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 13, 'Electronic', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 14, 'Funk', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 15, 'Heavy Metal', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 16, 'House', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 17, 'Jazz', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 18, 'New Age', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 19, 'Oldies', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 20, 'Pop', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 21, 'Reggae', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 22, 'R&B/Urban', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 23, 'Rock', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 24, 'Smooth Jazz', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 25, 'Slow', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 26, 'Techno', 0, 0 );" ) );
query.Add( wxT( "INSERT OR IGNORE INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) VALUES( 27, 'Top 40', 0, 0 );" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS radiostations( radiostation_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"radiostation_scid INTEGER, radiostation_source INTEGER, radiostation_genreid INTEGER, " \
"radiostation_name VARCHAR COLLATE NOCASE, radiostation_link VARCHAR, radiostation_type VARCHAR, " \
"radiostation_br INTEGER, radiostation_lc INTEGER, radiostation_ct VARCHAR );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_scid' on radiostations (radiostation_scid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_genreid' on radiostations (radiostation_source,radiostation_genreid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_lc' on radiostations (radiostation_lc ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_type' on radiostations (radiostation_type ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_ct' on radiostations (radiostation_ct ASC);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS radiolabels( radiolabel_id INTEGER PRIMARY KEY AUTOINCREMENT, radiolabel_name VARCHAR COLLATE NOCASE);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS radiosetlabels( radiosetlabel_id INTEGER PRIMARY KEY AUTOINCREMENT, radiosetlabel_labelid INTEGER, radiosetlabel_stationid INTEGER);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiosetlabel_labelid' on radiosetlabels (radiosetlabel_labelid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiosetlabel_stationidid' on radiosetlabels (radiosetlabel_stationid ASC);" ) );
int Count = query.Count();
for( int Index = 0; Index < Count; Index++ )
{
ExecuteUpdate( query[ Index ] );
}
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
m_StationsOrder = Config->ReadNum( CONFIG_KEY_RADIOS_STATIONS_ORDER, 0, CONFIG_PATH_RADIOS );
m_StationsOrderDesc = Config->ReadBool( CONFIG_KEY_RADIOS_STATIONS_ORDERDESC, false, CONFIG_PATH_RADIOS );
}
m_RadioSource = guRADIO_SOURCE_SHOUTCAST_GENRE;
m_RaTeFilters.Empty();
m_RaGeFilters.Empty();
m_RaLaFilters.Empty();
}
// -------------------------------------------------------------------------------- //
guDbRadios::~guDbRadios()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
Config->WriteNum( CONFIG_KEY_RADIOS_STATIONS_ORDER, m_StationsOrder, CONFIG_PATH_RADIOS );
Config->WriteBool( CONFIG_KEY_RADIOS_STATIONS_ORDERDESC, m_StationsOrderDesc, CONFIG_PATH_RADIOS );
}
}
// -------------------------------------------------------------------------------- //
int guDbRadios::GetRadioFiltersCount( void ) const
{
return m_RaTeFilters.Count() | m_RaGeFilters.Count() | m_RaLaFilters.Count();
}
// -------------------------------------------------------------------------------- //
wxString inline RadioTextFilterToSQL( const wxArrayString &textfilters, const int source )
{
long count;
wxString RetVal = wxEmptyString;
if( ( count = textfilters.Count() ) )
{
for( int index = 0; index < count; index++ )
{
if( source == guRADIO_SOURCE_USER )
{
RetVal += wxT( "radiostation_name LIKE '%" ) + escape_query_str( textfilters[ index ] ) + wxT( "%' AND " );
}
else
{
RetVal += wxT( "( radiogenre_name LIKE '%" ) + escape_query_str( textfilters[ index ] ) + wxT( "%' OR " );
RetVal += wxT( " radiostation_name LIKE '%" ) + escape_query_str( textfilters[ index ] ) + wxT( "%' ) AND " );
}
}
RetVal = RetVal.RemoveLast( 4 );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString guDbRadios::RadioFiltersSQL( void )
{
wxString query;
wxString RetVal = wxEmptyString;
if( m_RaTeFilters.Count() )
{
RetVal += RadioTextFilterToSQL( m_RaTeFilters, m_RadioSource );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbRadios::GetRadioGenresList( const int source, const wxArrayInt &ids, guListItems * listitems, wxArrayInt * radioflags )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( ids.Count() )
{
query = wxT( "SELECT radiogenre_id, radiogenre_name, radiogenre_flags FROM radiogenres WHERE " );
query += wxString::Format( wxT( "radiogenre_source = %i AND " ), source );
query += ArrayToFilter( ids, wxT( "radiogenre_id" ) );
query += wxT( " ORDER BY radiogenre_name COLLATE NOCASE;" );
//guLogMessage( query );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
listitems->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
if( radioflags )
radioflags->Add( dbRes.GetInt( 2 ) );
}
dbRes.Finalize();
}
}
// -------------------------------------------------------------------------------- //
void guDbRadios::GetRadioGenres( const int source, guListItems * radiogenres, bool AllowFilter, wxArrayInt * radioflags )
{
wxString query;
wxSQLite3ResultSet dbRes;
//if( !AllowFilter || !GetRadioFiltersCount() )
if( !AllowFilter || ( !m_RaTeFilters.Count() && !m_RaLaFilters.Count() ) )
{
query = wxT( "SELECT radiogenre_id, radiogenre_name, radiogenre_flags FROM radiogenres " );
query += wxString::Format( wxT( "WHERE radiogenre_source = %i " ), source );
query += wxT( "ORDER BY radiogenre_name COLLATE NOCASE;" );
}
else
{
query = wxT( "SELECT DISTINCT radiogenre_id, radiogenre_name, radiogenre_flags FROM radiogenres, radiostations " );
query += wxString::Format( wxT( "WHERE radiogenre_source = %i " ), source );
query += wxT( "AND radiogenre_id = radiostation_genreid " );
if( m_RaTeFilters.Count() )
{
query += wxT( " AND " );
query += RadioFiltersSQL();
}
if( m_RaLaFilters.Count() )
{
query += wxT( " AND radiostation_scid IN ( SELECT DISTINCT radiosetlabel_stationid FROM radiosetlabels WHERE " );
query += ArrayToFilter( m_RaLaFilters, wxT( "radiosetlabel_labelid" ) );
query += wxT( " )" );
}
query += wxT( " ORDER BY radiogenre_name COLLATE NOCASE;" );
}
//guLogMessage( query );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
radiogenres->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
if( radioflags )
radioflags->Add( dbRes.GetInt( 2 ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
int guDbRadios::AddRadioGenre( const wxString &GenreName, const int source, const int flags )
{
wxString query;
query = wxT( "INSERT INTO radiogenres( radiogenre_id, radiogenre_name, radiogenre_source, radiogenre_flags ) " );
query += wxString::Format( wxT( "VALUES( NULL, '%s', %i, %i );" ),
escape_query_str( GenreName ).c_str(),
source, flags );
if( ExecuteUpdate( query ) == 1 )
{
return GetLastRowId();
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::SetRadioGenre( const int genreid, const wxString &name, const int source, const int flags )
{
wxString query;
query = wxString::Format( wxT( "UPDATE radiogenres SET radiogenre_name = '%s', radiogenre_source = %i, " \
"radiogenre_flags = %i WHERE radiogenre_id = %u;" ),
escape_query_str( name ).c_str(), source, flags, genreid );
return ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
int guDbRadios::DelRadioGenre( const int GenreId )
{
wxString query;
query = query.Format( wxT( "DELETE FROM radiogenres WHERE radiogenre_id = %u;" ), GenreId );
if( ExecuteUpdate( query ) )
{
query = query.Format( wxT( "DELETE FROM radiostations WHERE radiostation_genreid = %u;" ), GenreId );
if( ExecuteUpdate( query ) )
return 1;
}
return 0;
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRaTeFilters( const wxArrayString &NewTeFilters )
{
m_RaTeFilters = NewTeFilters;
m_RaLaFilters.Empty();
m_RaGeFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioLabelsFilters( const wxArrayInt &filters )
{
if( filters.Index( 0 ) != wxNOT_FOUND )
{
m_RaLaFilters.Empty();
}
else
{
m_RaLaFilters = filters;
}
m_RaGeFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioGenresFilters( const wxArrayInt &filters )
{
if( filters.Index( 0 ) != wxNOT_FOUND )
{
m_RaGeFilters.Empty();
}
else
{
m_RaGeFilters = filters;
}
//m_RadioSource = false;
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioSourceFilter( int source )
{
m_RadioSource = source;
m_RaGeFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioGenres( const wxArrayString &Genres )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString GenreName;
query = wxT( "DELETE FROM radiogenres;" );
ExecuteUpdate( query );
int count = Genres.Count();
for( int index = 0; index < count; index++ )
{
GenreName = Genres[ index ];
escape_query_str( &GenreName );
query = wxString::Format( wxT( "INSERT INTO radiogenres( radiogenre_id, radiogenre_name ) "\
"VALUES( NULL, '%s' );" ), GenreName.c_str() );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioStationsOrder( int order )
{
if( m_StationsOrder != order )
{
m_StationsOrder = order;
m_StationsOrderDesc = ( order != 0 );
}
else
m_StationsOrderDesc = !m_StationsOrderDesc;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::GetUserRadioStations( guRadioStations * stations )
{
wxString query;
wxSQLite3ResultSet dbRes;
guRadioStation * Station;
query = wxT( "SELECT DISTINCT radiostation_name, radiostation_link " \
"FROM radiostations WHERE radiostation_source = 1 " );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Station = new guRadioStation();
Station->m_Name = dbRes.GetString( 0 );
Station->m_Link = dbRes.GetString( 1 );
stations->Add( Station );
}
dbRes.Finalize();
return stations->Count();
}
// -------------------------------------------------------------------------------- //
int guDbRadios::GetRadioStations( guRadioStations * Stations )
{
wxString query;
wxString querydb;
wxString subquery;
wxSQLite3ResultSet dbRes;
guRadioStation * Station;
if( !GetRadioFiltersCount() )
{
query = wxT( "SELECT DISTINCT radiostation_name, radiostation_id, radiostation_scid, " \
"radiostation_source, radiostation_genreid, radiostation_link, radiostation_type, " \
"radiostation_br, radiostation_lc, radiostation_ct " \
"FROM radiostations WHERE " );
query += wxString::Format( wxT( "radiostation_source = %u " ), m_RadioSource );
query += wxT( "GROUP BY radiostation_name, radiostation_br " );
}
else
{
if( m_RadioSource == guRADIO_SOURCE_USER )
{
//SELECT * FROM radiostations, radiosetlabels WHERE radiosetlabel_stationid = radiostation_id AND radiosetlabel_labelid IN ( 1 )
query = wxT( "SELECT DISTINCT radiostation_name, radiostation_id, radiostation_scid, radiostation_source, radiostation_genreid, radiostation_link, radiostation_type, radiostation_br, radiostation_lc, radiostation_ct " );
querydb = wxT( "FROM radiostations " );
//else
wxString subquery = wxEmptyString;
if( m_RaLaFilters.Count() )
{
querydb += wxT( ", radiosetlabels " );
subquery += wxT( "WHERE radiostation_scid = radiosetlabel_stationid AND radiostation_source = 1" );
subquery += wxT( " AND " ) + ArrayToFilter( m_RaLaFilters, wxT( "radiosetlabel_labelid" ) );
}
else
{
subquery += wxT( "WHERE radiostation_source = 1 " );
}
if( m_RaTeFilters.Count() )
{
//querydb += wxT( ", radiogenres " );
//subquery += wxT( "AND radiostation_genreid = radiogenre_id " );
subquery += wxT( "AND " ) + RadioFiltersSQL();
}
subquery += wxT( "GROUP BY radiostation_name, radiostation_br " );
query = query + querydb + subquery;
}
else
{
//SELECT * FROM radiostations, radiosetlabels WHERE radiosetlabel_stationid = radiostation_id AND radiosetlabel_labelid IN ( 1 )
query = wxT( "SELECT DISTINCT radiostation_name, radiostation_id, radiostation_scid, radiostation_source, " \
"radiostation_genreid, radiostation_link, radiostation_type, radiostation_br, radiostation_lc, radiostation_ct " \
"FROM radiostations, radiogenres" );
//else
wxString subquery = wxEmptyString;
if( m_RaLaFilters.Count() )
{
query += wxT( ", radiosetlabels WHERE radiostation_genreid = radiogenre_id AND radiostation_scid = radiosetlabel_stationid AND " );
subquery += ArrayToFilter( m_RaLaFilters, wxT( "radiosetlabel_labelid" ) );
}
else
{
query += wxT( " WHERE radiostation_genreid = radiogenre_id " );
}
subquery += wxString::Format( wxT( " AND radiostation_source = %i " ), m_RadioSource );
if( m_RaGeFilters.Count() )
{
subquery += wxT( " AND " ) + ArrayToFilter( m_RaGeFilters, wxT( "radiostation_genreid" ) );
}
if( m_RaTeFilters.Count() )
{
subquery += wxT( " AND " ) + RadioFiltersSQL();
}
if( !subquery.IsEmpty() )
{
query = query + subquery;
}
query += wxT( "GROUP BY radiostation_name, radiostation_br " );
}
}
query += wxT( " ORDER BY " );
if( m_StationsOrder == guRADIOSTATIONS_ORDER_NAME )
query += wxT( "radiostation_name COLLATE NOCASE" );
else if( m_StationsOrder == guRADIOSTATIONS_ORDER_BITRATE )
query += wxT( "radiostation_br" );
else if( m_StationsOrder == guRADIOSTATIONS_ORDER_LISTENERS )
query += wxT( "radiostation_lc" );
else if( m_StationsOrder == guRADIOSTATIONS_ORDER_TYPE )
query += wxT( "radiostation_type" );
else //if( m_StationsOrder == guRADIOSTATIONS_COLUMN_NOWPLAYING )
query += wxT( "radiostation_ct" );
if( m_StationsOrderDesc )
query += wxT( " DESC;" );
//guLogMessage( wxT( "GetRadioStations\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Station = new guRadioStation();
Station->m_Name = dbRes.GetString( 0 );
Station->m_Id = dbRes.GetInt( 1 );
Station->m_SCId = dbRes.GetInt( 2 );
Station->m_Source = dbRes.GetInt( 3 );
Station->m_GenreId = dbRes.GetInt( 4 );
Station->m_Link = dbRes.GetString( 5 );
Station->m_Type = dbRes.GetString( 6 );
Station->m_BitRate = dbRes.GetInt( 7 );
Station->m_Listeners = dbRes.GetInt( 8 );
Station->m_NowPlaying = dbRes.GetString( 9 );
Stations->Add( Station );
}
dbRes.Finalize();
return Stations->Count();
}
// -------------------------------------------------------------------------------- //
int guDbRadios::DelRadioStations( int source, const wxArrayInt &radioids )
{
wxString query;
if( radioids.Count() )
{
query = wxString::Format( wxT( "DELETE FROM radiostations WHERE radiostation_source = %i AND " ), source );
query += ArrayToFilter( radioids, wxT( "radiostation_genreid" ) );
return ExecuteUpdate( query );
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::DelRadioStation( const int radioid )
{
wxString query;
query = wxString::Format( wxT( "DELETE FROM radiostations WHERE radiostation_id = %u" ), radioid );
return ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioStation( const guRadioStation * radiostation )
{
wxString query;
if( radiostation->m_Id != wxNOT_FOUND )
{
query = wxString::Format( wxT( "UPDATE radiostations SET " \
"radiostation_scid = %u, radiostation_source = %u, radiostation_genreid = %u, " \
"radiostation_name = '%s', radiostation_link = '%s', radiostation_type = '%s', " \
"radiostation_br = %u, radiostation_lc = %u, radiostation_ct = '%s' WHERE radiostation_id = %u;" ),
radiostation->m_SCId,
radiostation->m_Source,
radiostation->m_GenreId,
escape_query_str( radiostation->m_Name ).c_str(),
escape_query_str( radiostation->m_Link ).c_str(),
escape_query_str( radiostation->m_Type ).c_str(),
radiostation->m_BitRate,
radiostation->m_Listeners,
escape_query_str( radiostation->m_NowPlaying ).c_str(),
radiostation->m_Id );
}
else
{
query = wxString::Format( wxT( "INSERT INTO radiostations( radiostation_id, radiostation_scid, radiostation_source, radiostation_genreid, " \
"radiostation_name, radiostation_link, radiostation_type, radiostation_br, radiostation_lc, radiostation_ct ) " \
"VALUES( NULL, %u, %u, %u, '%s', '%s', '%s', %u, %u, '%s' );" ),
radiostation->m_SCId,
radiostation->m_Source,
radiostation->m_GenreId,
escape_query_str( radiostation->m_Name ).c_str(),
escape_query_str( radiostation->m_Link ).c_str(),
escape_query_str( radiostation->m_Type ).c_str(),
radiostation->m_BitRate,
radiostation->m_Listeners,
escape_query_str( radiostation->m_NowPlaying ).c_str() );
}
//guLogMessage( wxT( "SetRadioStation:\n%s" ), query.c_str() );
ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioStations( const guRadioStations * RadioStations )
{
int count = RadioStations->Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
SetRadioStation( &RadioStations->Item( index ) );
}
}
}
// -------------------------------------------------------------------------------- //
bool guDbRadios::GetRadioStation( const int id, guRadioStation * radiostation )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT radiostation_id, radiostation_scid, radiostation_source, radiostation_genreid, " \
"radiostation_name, radiostation_link, radiostation_type, radiostation_br, radiostation_lc " \
"FROM radiostations WHERE " );
query += wxString::Format( wxT( "radiostation_id = %u LIMIT 1;" ), id );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
radiostation->m_Id = dbRes.GetInt( 0 );
radiostation->m_SCId = dbRes.GetInt( 1 );
radiostation->m_Source = dbRes.GetInt( 2 );
radiostation->m_GenreId = dbRes.GetInt( 3 );
radiostation->m_Name = dbRes.GetString( 4 );
radiostation->m_Link = dbRes.GetString( 5 );
radiostation->m_Type = dbRes.GetString( 6 );
radiostation->m_BitRate = dbRes.GetInt( 7 );
radiostation->m_Listeners = dbRes.GetInt( 8 );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDbRadios::RadioStationExists( const int shoutcastid )
{
wxString query;
wxSQLite3ResultSet dbRes;
bool RetVal;
query = wxString::Format( wxT( "SELECT radiostation_id WHERE radiostation_scid = %i LIMIT 1;" ), shoutcastid );
dbRes = ExecuteQuery( query );
RetVal = dbRes.NextRow();
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayInt guDbRadios::GetStationsSCIds( const wxArrayInt &stations )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxArrayInt RetVal;
query = wxT( "SELECT DISTINCT( radiostation_scid ) FROM radiostations " ) \
wxT( "WHERE radiostation_id IN " ) + ArrayIntToStrList( stations );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
RetVal.Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
guArrayListItems guDbRadios::GetStationsLabels( const wxArrayInt &Stations )
{
wxString query;
wxSQLite3ResultSet dbRes;
guArrayListItems RetVal;
guArrayListItem * CurItem = NULL;
int Id;
int count = Stations.Count();
for( int index = 0; index < count; index++ )
{
Id = Stations[ index ];
RetVal.Add( new guArrayListItem( Id ) );
}
query = wxT( "SELECT radiosetlabel_stationid, radiosetlabel_labelid FROM radiosetlabels " ) \
wxT( "WHERE radiosetlabel_stationid IN " ) + ArrayIntToStrList( Stations );
query += wxT( " ORDER BY radiosetlabel_stationid, radiosetlabel_labelid;" );
//guLogMessage( query );
dbRes = ExecuteQuery( query );
int index = 0;
CurItem = &RetVal[ index ];
while( dbRes.NextRow() )
{
Id = dbRes.GetInt( 0 );
if( CurItem->GetId() != Id )
{
index = 0;
while( CurItem->GetId() != Id )
{
CurItem = &RetVal[ index ];
index++;
}
}
CurItem->AddData( dbRes.GetInt( 1 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbRadios::SetRadioStationsLabels( const guArrayListItems &labelsets )
{
wxString query;
wxArrayInt Stations;
wxArrayInt Labels;
int StaIndex;
int StaCount;
int LaIndex;
int LaCount;
if( ( StaCount = labelsets.Count() ) )
{
for( StaIndex = 0; StaIndex < StaCount; StaIndex++ )
{
Stations.Add( labelsets[ StaIndex ].GetId() );
}
query = wxT( "DELETE FROM radiosetlabels " \
"WHERE radiosetlabel_stationid IN " ) + ArrayIntToStrList( Stations );
ExecuteUpdate( query );
for( StaIndex = 0; StaIndex < StaCount; StaIndex++ )
{
Labels = labelsets[ StaIndex ].GetData();
LaCount = Labels.Count();
for( LaIndex = 0; LaIndex < LaCount; LaIndex++ )
{
query = wxString::Format( wxT( "INSERT INTO radiosetlabels( radiosetlabel_labelid, radiosetlabel_stationid ) " \
"VALUES( %u, %u );" ), Labels[ LaIndex ], Stations[ StaIndex ] );
ExecuteUpdate( query );
}
}
}
}
// -------------------------------------------------------------------------------- //
int guDbRadios::GetRadioLabelsSongs( const wxArrayInt &Labels, guTrackArray * Songs )
{
wxString subquery;
wxString query;
wxSQLite3ResultSet dbRes;
// guTrack * Song;
if( Labels.Count() )
{
subquery = ArrayIntToStrList( Labels );
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
void guDbRadios::GetRadioLabels( guListItems * Labels, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT radiolabel_id, radiolabel_name FROM radiolabels ORDER BY " );
query += FullList ? wxT( "radiolabel_id;" ) : wxT( "radiolabel_name COLLATE NOCASE;" );
//guLogMessage( query );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Labels->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
// return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::AddRadioLabel( wxString LabelName )
{
wxString query;
escape_query_str( &LabelName );
query = wxT( "INSERT INTO radiolabels( radiolabel_id, radiolabel_name ) VALUES( NULL, '" ) +
LabelName + wxT( "');" );
if( ExecuteUpdate( query ) == 1 )
{
return GetLastRowId();
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::SetRadioLabelName( const int LabelId, wxString LabelName )
{
wxString query;
escape_query_str( &LabelName );
query = query.Format( wxT( "UPDATE radiolabels SET radiolabel_name = '%s' WHERE radiolabel_id = %u;" ), LabelName.c_str(), LabelId );
if( ExecuteUpdate( query ) == 1 )
{
return GetLastRowId();
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbRadios::DelRadioLabel( const int labelid )
{
wxString query;
query = query.Format( wxT( "DELETE FROM radiolabels WHERE radiolabel_id = %u;" ), labelid );
if( ExecuteUpdate( query ) )
{
query = query.Format( wxT( "DELETE FROM radiosetlabels WHERE radiosetlabel_labelid = %u;" ), labelid );
if( ExecuteUpdate( query ) )
{
return 1;
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 32,313
|
C++
|
.cpp
| 699
| 40.311874
| 228
| 0.585571
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,552
|
DbLibrary.cpp
|
anonbeat_guayadeque/src/db/DbLibrary.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "DbLibrary.h"
#include "AlbumBrowser.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "DynamicPlayList.h"
#include "LibUpdate.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "MD5.h"
#include "PlayerPanel.h"
#include "TagInfo.h"
#include "Utils.h"
#include "TreePanel.h"
#include <wx/mstream.h>
#include <wx/wfstream.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guTrackArray )
WX_DEFINE_OBJARRAY( guListItems )
WX_DEFINE_OBJARRAY( guArrayListItems )
WX_DEFINE_OBJARRAY( guAlbumItems )
WX_DEFINE_OBJARRAY( guCoverInfos )
WX_DEFINE_OBJARRAY( guAS_SubmitInfoArray )
#define GU_CURRENT_DBVERSION "21"
// -------------------------------------------------------------------------------- //
// Various functions
// -------------------------------------------------------------------------------- //
wxString GetSongsDBNamesSQL( const int order );
wxString GetSongsSortSQL( const int order, const bool orderdesc );
// -------------------------------------------------------------------------------- //
int guAlbumItemSearch( const guAlbumItems &items, int start, int end, int id )
{
if( start >= end && items[ start ].m_Id != id )
{
return -1;
}
else
{
int MidPos = ( ( start + end ) / 2 );
if( items[ MidPos ].m_Id == id )
return MidPos;
else if( id > items[ MidPos ].m_Id )
return guAlbumItemSearch( items, MidPos + 1, end, id );
else
return guAlbumItemSearch( items, start, MidPos - 1, id );
}
}
// -------------------------------------------------------------------------------- //
guAlbumItem * guAlbumItemGetItem( guAlbumItems &items, int id )
{
int index;
int count = items.Count();
if( count )
{
index = guAlbumItemSearch( items, 0, count - 1, id );
if( index != wxNOT_FOUND )
return &items[ index ];
guLogError( wxT( "Could not find in cache the albumid : %i" ), id );
}
return NULL;
}
// -------------------------------------------------------------------------------- //
wxString guAlbumItemsGetName( const guAlbumItems &items, int id )
{
int index;
int count = items.Count();
if( count )
{
index = guAlbumItemSearch( items, 0, count - 1, id );
if( index != wxNOT_FOUND )
return items[ index ].m_Name;
guLogError( wxT( "Could not find in cache the albumid : %i" ), id );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
int guAlbumItemsGetCoverId( const guAlbumItems &items, int id )
{
int index;
int count = items.Count();
if( count )
{
index = guAlbumItemSearch( items, 0, count - 1, id );
if( index != wxNOT_FOUND )
return items[ index ].m_CoverId;
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guListItemSearch( const guListItems &items, int start, int end, int id )
{
if( start >= end && items[ start ].m_Id != id )
{
return -1;
}
else
{
int MidPos = ( ( start + end ) / 2 );
if( items[ MidPos ].m_Id == id )
return MidPos;
else if( id > items[ MidPos ].m_Id )
return guListItemSearch( items, MidPos + 1, end, id );
else
return guListItemSearch( items, start, MidPos - 1, id );
}
}
// -------------------------------------------------------------------------------- //
wxString guListItemsGetName( const guListItems &items, int id )
{
int index;
int count = items.Count();
if( count )
{
index = guListItemSearch( items, 0, count - 1, id );
if( index != wxNOT_FOUND )
return items[ index ].m_Name;
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
wxArrayInt GetArraySameItems( const wxArrayInt &Source, const wxArrayInt &Oper )
{
wxArrayInt RetVal = Source;
int count = RetVal.Count();
if( count )
{
for( int index = count - 1; index >= 0; index-- )
{
if( Oper.Index( RetVal[ index ] ) == wxNOT_FOUND )
{
RetVal.RemoveAt( index );
}
}
}
return RetVal;
};
// -------------------------------------------------------------------------------- //
wxArrayInt GetArrayDiffItems( const wxArrayInt &Source, const wxArrayInt &Oper )
{
wxArrayInt RetVal = Source;
int count = RetVal.Count();
if( count )
{
for( int index = count - 1; index >= 0; index-- )
{
if( Oper.Index( RetVal[ index ] ) != wxNOT_FOUND )
{
RetVal.RemoveAt( index );
}
}
}
return RetVal;
};
// -------------------------------------------------------------------------------- //
wxString TextFilterToSQL( const wxArrayString &TeFilters )
{
int count;
wxString RetVal;
if( ( count = TeFilters.Count() ) )
{
for( int index = 0; index < count; index++ )
{
wxString Filter = escape_query_str( TeFilters[ index ] );
RetVal += wxT( "( song_name LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_albumartist LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_artist LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_composer LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_album LIKE '%" ) + Filter + wxT( "%' ) " );
RetVal += wxT( "AND " );
}
RetVal = RetVal.RemoveLast( 4 );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString LabelFilterToSQL( const wxArrayInt &LaFilters )
{
int count;
wxString subquery;
wxString RetVal = wxEmptyString;
if( ( count = LaFilters.Count() ) )
{
subquery = wxT( "(" );
for( int index = 0; index < count; index++ )
{
subquery += wxString::Format( wxT( "%u," ), LaFilters[ index ] );
}
subquery = subquery.RemoveLast( 1 ) + wxT( ")" );
RetVal += wxT( "( (song_artistid IN ( SELECT settag_artistid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_artistid > 0 ) ) OR" );
RetVal += wxT( " (song_albumid IN ( SELECT settag_albumid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_albumid > 0 ) ) OR" );
RetVal += wxT( " (song_id IN ( SELECT settag_songid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_songid > 0 ) ) )" );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
// guTrack
// -------------------------------------------------------------------------------- //
bool guTrack::ReadFromFile( const wxString &filename )
{
bool RetVal = false;
guTagInfo * TagInfo;
TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
//guLogMessage( wxT( "FileName: '%s'" ), filename.c_str() );
m_Path = wxPathOnly( filename );
if( !m_Path.EndsWith( wxT( "/" ) ) )
m_Path += '/';
//guLogMessage( wxT( "PathName: %s" ), m_Path.c_str() );
if( TagInfo->Read() )
{
m_Composer = TagInfo->m_Composer;
m_ArtistName = TagInfo->m_ArtistName;
m_AlbumArtist = TagInfo->m_AlbumArtist;
m_AlbumName = TagInfo->m_AlbumName;
m_GenreName = TagInfo->m_GenreName;
m_SongName = TagInfo->m_TrackName;
m_Number = TagInfo->m_Track;
m_Year = TagInfo->m_Year;
m_Length = TagInfo->m_Length;
m_Bitrate = TagInfo->m_Bitrate;
m_Comments = TagInfo->m_Comments;
m_Disk = TagInfo->m_Disk;
}
else
{
guLogError( wxT( "Cant read tags from '%s'" ), filename.c_str() );
}
m_PathId = wxNOT_FOUND;
if( m_ArtistName.IsEmpty() )
m_ArtistName = _( "Unknown" );
m_ArtistId = wxNOT_FOUND;
m_AlbumArtistId = wxNOT_FOUND;;
if( m_AlbumName.IsEmpty() && !m_Path.IsEmpty() )
m_AlbumName = m_Path.BeforeLast( wxT( '/' ) ).AfterLast( wxT( '/' ) );
m_AlbumId = wxNOT_FOUND;;
m_CoverId = 0;
if( m_GenreName.IsEmpty() )
m_GenreName = _( "Unknown" );
m_GenreId = wxNOT_FOUND;;
m_FileName = filename;
m_FileSize = guGetFileSize( filename );
if( m_SongName.IsEmpty() )
m_SongName = m_FileName.AfterLast( wxT( '/' ) ).BeforeLast( wxT( '.' ) );
m_SongId = wxNOT_FOUND;;
m_Rating = wxNOT_FOUND;
RetVal = true;
delete TagInfo;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
// guDbLibrary
// -------------------------------------------------------------------------------- //
guDbLibrary::guDbLibrary() : guDb()
{
m_MediaViewer = NULL;
m_NeedUpdate = false;
m_LastAlbum = wxT( "__Gu4y4d3qu3__" );
m_LastGenre = wxT( "__Gu4y4d3qu3__" );
m_LastCoverId = wxNOT_FOUND;
m_LastArtist = wxT( "__Gu4y4d3qu3__" );
m_LastArtistId = wxNOT_FOUND;
m_LastAlbumArtist = wxT( "__Gu4y4d3qu3__" );
m_LastAlbumArtistId = wxNOT_FOUND;
m_LastComposer = wxT( "__Gu4y4d3qu3__" );
m_LastComposerId = wxNOT_FOUND;
CheckDbVersion();
}
// -------------------------------------------------------------------------------- //
guDbLibrary::guDbLibrary( const wxString &dbname ) : guDb( dbname )
{
m_MediaViewer = NULL;
m_NeedUpdate = false;
m_LastAlbum = wxT( "__Gu4y4d3qu3__" );
m_LastGenre = wxT( "__Gu4y4d3qu3__" );
m_LastCoverId = wxNOT_FOUND;
m_LastArtist = wxT( "__Gu4y4d3qu3__" );
m_LastArtistId = wxNOT_FOUND;
m_LastAlbumArtist = wxT( "__Gu4y4d3qu3__" );
m_LastAlbumArtistId = wxNOT_FOUND;
m_LastComposer = wxT( "__Gu4y4d3qu3__" );
m_LastComposerId = wxNOT_FOUND;
CheckDbVersion();
}
// -------------------------------------------------------------------------------- //
guDbLibrary::guDbLibrary( guDb * db ) : guDb()
{
m_MediaViewer = NULL;
m_NeedUpdate = false;
m_LastAlbum = wxT( "__Gu4y4d3qu3__" );
m_LastGenre = wxT( "__Gu4y4d3qu3__" );
m_LastCoverId = wxNOT_FOUND;
m_LastArtist = wxT( "__Gu4y4d3qu3__" );
m_LastArtistId = wxNOT_FOUND;
m_LastAlbumArtist = wxT( "__Gu4y4d3qu3__" );
m_LastAlbumArtistId = wxNOT_FOUND;
m_LastComposer = wxT( "__Gu4y4d3qu3__" );
m_LastComposerId = wxNOT_FOUND;
m_Db = db->GetDb();
}
// -------------------------------------------------------------------------------- //
guDbLibrary::~guDbLibrary()
{
Close();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetMediaViewer( guMediaViewer * mediaviewer )
{
m_MediaViewer = mediaviewer;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetDbVersion( void )
{
wxString query;
wxSQLite3ResultSet dbRes;
unsigned long RetVal = 0;
query = wxT( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'Version';" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
dbRes.Finalize();
query = wxT( "SELECT version FROM Version;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
}
else
{
query = wxT( "CREATE TABLE Version( version INTEGER );" );
ExecuteUpdate( query );
}
dbRes.Finalize();
return RetVal;
}
/*
// -------------------------------------------------------------------------------- //
void guDbLibrary::DoCleanUp( void )
{
wxString query;
wxArrayInt SongsToDel;
wxArrayInt CoversToDel;
wxSQLite3ResultSet dbRes;
wxString FileName;
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString LibPaths = Config->ReadAStr( wxT( "LibPath" ), wxEmptyString, wxT( "libpaths" ) );
CheckSymLinks( LibPaths );
query = wxT( "SELECT DISTINCT song_id, song_filename, song_path FROM songs " );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
FileName = dbRes.GetString( 2 ) + wxT( "/" ) + dbRes.GetString( 1 );
if( !wxFileExists( FileName ) || !CheckFileLibPath( LibPaths, FileName ) )
{
SongsToDel.Add( dbRes.GetInt( 0 ) );
}
}
dbRes.Finalize();
query = wxT( "SELECT DISTINCT cover_id, cover_path FROM covers;" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
if( !wxFileExists( dbRes.GetString( 1 ) ) )
{
CoversToDel.Add( dbRes.GetInt( 0 ) );
}
}
dbRes.Finalize();
CleanItems( SongsToDel, CoversToDel );
}
*/
// -------------------------------------------------------------------------------- //
void guDbLibrary::CleanFiles( const wxArrayString &Files )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxArrayInt Tracks;
wxArrayInt Covers;
int Count = Files.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( guIsValidAudioFile( Files[ Index ] ) )
{
int TrackId = FindTrackFile( Files[ Index ], NULL );
if( TrackId )
Tracks.Add( TrackId );
}
else if( guIsValidImageFile( Files[ Index ].Lower() ) )
{
query = wxString::Format( wxT( "SELECT cover_id FROM covers WHERE cover_path = '%s'" ), escape_query_str( Files[ Index ] ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
Covers.Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
}
}
//
CleanItems( Tracks, Covers );
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::CleanItems( const wxArrayInt &tracks, const wxArrayInt &covers )
{
wxString query;
if( tracks.Count() )
{
query = wxT( "DELETE FROM songs WHERE " ) + ArrayToFilter( tracks, wxT( "song_id" ) );
ExecuteUpdate( query );
}
if( covers.Count() )
{
query = wxT( "DELETE FROM covers WHERE " ) + ArrayToFilter( covers, wxT( "cover_id" ) );
ExecuteUpdate( query );
}
// Delete all posible orphan entries
// query = wxT( "DELETE FROM genres WHERE genre_id NOT IN ( SELECT DISTINCT song_genreid FROM songs );" );
// ExecuteUpdate( query );
// query = wxT( "DELETE FROM artists WHERE artist_id NOT IN ( SELECT DISTINCT song_artistid FROM songs );" );
// ExecuteUpdate( query );
// query = wxT( "DELETE FROM albums WHERE album_id NOT IN ( SELECT DISTINCT song_albumid FROM songs );" );
// ExecuteUpdate( query );
query = wxT( "DELETE FROM covers WHERE cover_id NOT IN ( SELECT DISTINCT song_coverid FROM songs );" );
ExecuteUpdate( query );
// query = wxT( "DELETE FROM paths WHERE path_id NOT IN ( SELECT DISTINCT song_pathid FROM songs );" );
// ExecuteUpdate( query );
query = wxT( "DELETE FROM plsets WHERE plset_type = 0 AND plset_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" );
ExecuteUpdate( query );
query = wxT( "DELETE FROM settags WHERE settag_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" );
ExecuteUpdate( query );
//LoadCache();
}
// -------------------------------------------------------------------------------- //
bool guDbLibrary::CheckDbVersion( void )
{
wxArrayString query;
unsigned long dbVer;
bool NeedVacuum = false;
dbVer = GetDbVersion();
guLogMessage( wxT( "Library Db Version %lu" ), dbVer );
switch( dbVer )
{
case 4 :
{
Close();
guLogMessage( wxT( "Update of database needed. Old database renamed to guayadeque.db.save" ) );
wxRenameFile( m_DbName, m_DbName + wxT( ".save" ), true );
m_NeedUpdate = true;
Open( m_DbName );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS Version( version INTEGER );" ) );
}
case 0 :
{
// the database is going to be created... Reset the last update
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
Config->WriteStr( CONFIG_KEY_GENERAL_LAST_UPDATE, wxEmptyString, CONFIG_PATH_GENERAL );
}
query.Add( wxT( "CREATE TABLE IF NOT EXISTS songs( song_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"song_name VARCHAR COLLATE NOCASE, song_genreid INTEGER, song_genre VARCHAR COLLATE NOCASE, " \
"song_artistid INTEGER, song_artist VARCHAR COLLATE NOCASE, song_albumartistid INTEGER, " \
"song_albumartist VARCHAR COLLATE NOCASE, song_composerid INTEGER, " \
"song_composer VARCHAR COLLATE NOCASE, song_albumid INTEGER, song_album VARCHAR COLLATE NOCASE, " \
"song_pathid INTEGER, song_path VARCHAR, song_filename VARCHAR, " \
"song_format VARCHAR(8) COLLATE NOCASE, song_disk VARCHAR COLLATE NOCASE, " \
"song_number INTEGER(3), song_year INTEGER(4), song_comment VARCHAR COLLATE NOCASE, " \
"song_coverid INTEGER, song_offset INTEGER, song_length INTEGER, song_bitrate INTEGER, " \
"song_rating INTEGER DEFAULT -1, song_playcount INTEGER DEFAULT 0, song_addedtime INTEGER, " \
"song_lastplay INTEGER, song_filesize INTEGER, song_albumsku VARCHAR, song_coverlink VARCHAR );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_name on songs( song_name ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumid on songs( song_albumid,song_artist,song_year DESC, song_album, song_disk )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composerid on songs( song_composerid, song_composer )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artistid on songs( song_artistid, song_artist )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartistid on songs( song_albumartistid, song_albumartist )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genreid on songs( song_genreid, song_genre )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_pathid on songs( song_pathid ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_length on songs( song_length ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_bitrate on songs( song_bitrate ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_rating on songs( song_rating ASC )" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_rating_desc ON songs( song_rating DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_playcount on songs( song_playcount ASC )" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime on songs( song_addedtime ASC )" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime_desc ON songs( song_addedtime DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_lastplay on songs( song_lastplay ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composerid on songs( song_composerid ASC )" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composerid_desc ON songs( song_composerid DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_number ON songs( song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_path ON songs( song_path ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_path_filename ON songs( song_path, song_filename )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_format ON songs( song_format ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genre ON songs( song_genre,song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genre_desc ON songs( song_genre DESC,song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composer ON songs( song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composer_desc ON songs( song_composer DESC,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artist ON songs( song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artist_desc ON songs( song_artist DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartist ON songs( song_albumartist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartist_desc ON songs( song_albumartist DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_album ON songs( song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_album_desc ON songs( song_album DESC,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_disk ON songs( song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_disk_desc ON songs( song_disk DESC,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_year ON songs( song_year,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_year_desc ON songs( song_year DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime ON songs( song_addedtime,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime_desc ON songs( song_addedtime DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS tags( tag_id INTEGER PRIMARY KEY AUTOINCREMENT, tag_name VARCHAR COLLATE NOCASE );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'tag_id' on tags (tag_id ASC);" ) );
query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'tag_name' on tags (tag_name ASC);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS settags( settag_tagid INTEGER, settag_artistid INTEGER, settag_albumid INTEGER, settag_songid INTEGER );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'settag_tagid' on settags (settag_tagid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'settag_artistid' on settags (settag_artistid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'settag_albumid' on settags (settag_albumid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'settag_songid' on settags (settag_songid ASC);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS playlists( playlist_id INTEGER PRIMARY KEY AUTOINCREMENT, playlist_name VARCHAR COLLATE NOCASE, " \
"playlist_type INTEGER(2), playlist_limited BOOLEAN, playlist_limitvalue INTEGER, playlist_limittype INTEGER(2), " \
"playlist_sorted BOOLEAN, playlist_sorttype INTEGER(2), playlist_sortdesc BOOLEAN, playlist_anyoption BOOLEAN, " \
"playlist_path VARCHAR );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'playlist_id' on playlists (playlist_id ASC);" ) );
wxString querystr = wxT( "INSERT INTO playlists( playlist_id, playlist_name, playlist_type, " \
"playlist_limited, playlist_limitvalue, playlist_limittype, " \
"playlist_sorted, playlist_sorttype, playlist_sortdesc, playlist_anyoption ) " \
"VALUES( NULL, '" );
querystr += _( "Recently added tracks" );
querystr += wxT( "', 1, 0, 0, 0, 1, 12, 1, 0 );" );
query.Add( querystr );
querystr = wxT( "INSERT INTO playlists( playlist_id, playlist_name, playlist_type, " \
"playlist_limited, playlist_limitvalue, playlist_limittype, " \
"playlist_sorted, playlist_sorttype, playlist_sortdesc, playlist_anyoption ) " \
"VALUES( NULL, '" );
querystr += _( "Last played tracks" );
querystr += wxT( "', 1, 0, 0, 0, 1, 11, 1, 0 );" );
query.Add( querystr );
querystr = wxT( "INSERT INTO playlists( playlist_id, playlist_name, playlist_type, " \
"playlist_limited, playlist_limitvalue, playlist_limittype, " \
"playlist_sorted, playlist_sorttype, playlist_sortdesc, playlist_anyoption ) " \
"VALUES( NULL, '" );
querystr += _( "Best rated tracks" );
querystr += wxT( "', 1, 0, 0, 0, 1, 8, 1, 0 );" );
query.Add( querystr );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS plsets( plset_id INTEGER PRIMARY KEY AUTOINCREMENT, plset_plid INTEGER, plset_songid INTEGER, " \
"plset_type INTEGER(2), plset_option INTEGER(2), plset_text TEXT(255), plset_number INTEGER, plset_option2 INTEGER );" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'plset_id' on plsets (plset_id ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'plset_plid' on plsets (plset_plid ASC);" ) );
query.Add( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, "
"plset_type, plset_option, plset_text, plset_number, plset_option2 ) " \
"VALUES( NULL, 1, 0, 14, 0, '', 1, 3 );" ) );
query.Add( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, " \
"plset_type, plset_option, plset_text, plset_number, plset_option2 ) " \
"VALUES( NULL, 2, 0, 13, 0, '', 1, 2 );" ) );
query.Add( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, " \
"plset_type, plset_option, plset_text, plset_number, plset_option2 ) " \
"VALUES( NULL, 3, 0, 10, 2, '', 4, 0 );" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS covers( cover_id INTEGER PRIMARY KEY AUTOINCREMENT, cover_path VARCHAR, cover_thumb BLOB, cover_midsize BLOB, cover_hash VARCHAR );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'cover_id' on covers (cover_id ASC);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS audioscs( audiosc_id INTEGER PRIMARY KEY AUTOINCREMENT, audiosc_artist VARCHAR(255), audiosc_album varchar(255), audiosc_track varchar(255), audiosc_playedtime INTEGER, audiosc_source char(1), audiosc_ratting char(1), audiosc_len INTEGER, audiosc_tracknum INTEGER, audiosc_mbtrackid INTEGER );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'audiosc_id' on audioscs (audiosc_id ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'audiosc_playedtime' on audioscs (audiosc_playedtime ASC);" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS deleted( delete_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"delete_path VARCHAR, delete_date INTEGER );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS delete_path on deleted(delete_path ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS delete_date on deleted(delete_date ASC);" ) );
}
case 5 :
{
// query.Add( wxT( "CREATE TABLE IF NOT EXISTS podcastchs( podcastch_id INTEGER PRIMARY KEY AUTOINCREMENT, "
// "podcastch_url VARCHAR, podcastch_title VARCHAR COLLATE NOCASE, podcastch_description VARCHAR, "
// "podcastch_language VARCHAR, podcastch_time INTEGER, podcastch_sumary VARCHAR, "
// "podcastch_author VARCHAR, podcastch_ownername VARCHAR, podcastch_owneremail VARCHAR, "
// "podcastch_category VARCHAR, podcastch_image VARCHAR, podcastch_downtype INTEGER, "
// "podcastch_downtext VARCHAR, podcastch_allowdel BOOLEAN );" ) );
// //query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'podcastch_id' on podcastchs(podcastch_id ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastch_title' on podcastchs(podcastch_title ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastch_url' on podcastchs(podcastch_url ASC);" ) );
//
// query.Add( wxT( "CREATE TABLE IF NOT EXISTS podcastitems( podcastitem_id INTEGER PRIMARY KEY AUTOINCREMENT, "
// "podcastitem_chid INTEGER, podcastitem_title VARCHAR COLLATE NOCASE, podcastitem_summary VARCHAR, "
// "podcastitem_author VARCHAR COLLATE NOCASE, podcastitem_enclosure VARCHAR, podcastitem_time INTEGER, "
// "podcastitem_file VARCHAR, podcastitem_filesize INTEGER, podcastitem_length INTEGER, "
// "podcastitem_addeddate INTEGER, podcastitem_playcount INTEGER, "
// "podcastitem_lastplay INTEGER, podcastitem_status INTEGER );" ) );
// //query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'podcastitem_id' on podcastitems(podcastitem_id ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_title' on podcastitems(podcastitem_title ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_file' on podcastitems(podcastitem_file ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_chid' on podcastitems(podcastitem_chid ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_time' on podcastitems(podcastitem_time ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_enclosure' on podcastitems(podcastitem_enclosure ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_author' on podcastitems(podcastitem_author ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'podcastitem_length' on podcastitems(podcastitem_length ASC);" ) );
}
case 6 :
{
if( dbVer > 4 )
{
query.Add( wxT( "DROP INDEX 'radiostation_id';" ) );
query.Add( wxT( "DROP INDEX 'radiostation_genreid';" ) );
query.Add( wxT( "DROP TABLE 'radiostations';" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS radiostations( radiostation_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"radiostation_scid INTEGER, radiostation_source INTEGER, radiostation_genreid INTEGER, " \
"radiostation_name VARCHAR, radiostation_link VARCHAR, radiostation_type VARCHAR, " \
"radiostation_br INTEGER, radiostation_lc INTEGER, radiostation_ct VARCHAR );" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_id' on radiostations (radiostation_id ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_genreid' on radiostations (radiostation_source,radiostation_genreid ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_lc' on radiostations (radiostation_lc ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_type' on radiostations (radiostation_type ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_ct' on radiostations (radiostation_ct ASC);" ) );
}
}
case 7 :
{
query.Add( wxT( "DROP TABLE 'covers';" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS covers( cover_id INTEGER PRIMARY KEY AUTOINCREMENT, cover_path VARCHAR(1024), cover_thumb BLOB, cover_midsize BLOB, cover_hash VARCHAR( 32 ) );" ) );
//query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'cover_id' on covers (cover_id ASC);" ) );
}
case 8 :
{
query.Add( wxT( "DELETE FROM covers;" ) );
}
case 9 :
{
if( dbVer > 4 )
{
query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_disk VARCHAR" ) );
query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_comment VARCHAR" ) );
//query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_composer VARCHAR(512)" ) );
}
}
case 10 :
{
if( dbVer > 4 )
{
query.Add( wxT( "UPDATE playlists SET playlist_sorttype = playlist_sorttype + 1 WHERE playlist_sorttype > 4;" ) );
query.Add( wxT( "UPDATE plsets SET plset_type = plset_type + 2 WHERE plset_type > 4;" ) );
}
}
case 11 :
{
// query.Add( wxT( "CREATE TABLE IF NOT EXISTS composers( composer_id INTEGER PRIMARY KEY AUTOINCREMENT, composer_name varchar(512) );" ) );
// query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'composer_id' on composers (composer_id ASC);" ) );
// query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'composer_name' on composers (composer_name ASC);" ) );
if( dbVer > 4 )
{
//query.Add( wxT( "ALTER TABLE songs DELETE COLUMN song_composer" ) );
query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_composerid INTEGER" ) );
}
m_NeedUpdate = true;
}
case 12 :
{
if( dbVer > 4 )
{
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'song_composerid' on songs( song_composerid ASC );" ) );
}
}
case 13 :
{
if( dbVer > 4 )
{
query.Add( wxT( "ALTER TABLE radiogenres ADD COLUMN radiogenre_source INTEGER" ) );
query.Add( wxT( "ALTER TABLE radiogenres ADD COLUMN radiogenre_flags INTEGER" ) );
query.Add( wxT( "UPDATE radiogenres SET radiogenre_source = 0;" ) );
query.Add( wxT( "UPDATE radiogenres SET radiogenre_flags = 0;" ) );
query.Add( wxT( "ALTER TABLE radiostations ADD COLUMN radiostation_source INTEGER" ) );
query.Add( wxT( "UPDATE radiostations SET radiostation_source = radiostation_isuser;" ) );
}
}
case 14 :
{
if( dbVer > 4 )
{
query.Add( wxT( "ALTER TABLE radiostations ADD COLUMN radiostation_ct VARCHAR" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_lc' on radiostations (radiostation_lc ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_type' on radiostations (radiostation_type ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'radiostation_ct' on radiostations (radiostation_ct ASC);" ) );
}
}
case 15 :
{
if( dbVer > 4 )
{
//query.Add( wxT( "VACUUM;" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS songs1( song_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"song_name VARCHAR COLLATE NOCASE, song_genreid INTEGER, song_genre VARCHAR COLLATE NOCASE, " \
"song_artistid INTEGER, song_artist VARCHAR COLLATE NOCASE, song_albumartistid INTEGER, " \
"song_albumartist VARCHAR COLLATE NOCASE, song_composerid INTEGER, song_composer VARCHAR COLLATE NOCASE, " \
"song_albumid INTEGER, song_album VARCHAR COLLATE NOCASE, song_pathid INTEGER, song_path VARCHAR, " \
"song_filename VARCHAR, song_format VARCHAR(8) COLLATE NOCASE, song_disk VARCHAR COLLATE NOCASE, " \
"song_number INTEGER(3), song_year INTEGER(4), song_comment VARCHAR COLLATE NOCASE, " \
"song_coverid INTEGER, song_offset INTEGER, song_length INTEGER, song_bitrate INTEGER, " \
"song_rating INTEGER DEFAULT -1, song_playcount INTEGER DEFAULT 0, song_addedtime INTEGER, " \
"song_lastplay INTEGER, song_filesize INTEGER );" ) );
query.Add( wxT( "INSERT INTO songs1( song_id, song_name, song_albumid, song_artistid, song_genreid, song_filename, " \
"song_pathid, song_number, song_disk, song_year, song_comment, song_composerid, song_length, " \
"song_bitrate, song_rating, song_playcount, song_addedtime, song_lastplay, song_filesize ) " \
"SELECT song_id, song_name, song_albumid, song_artistid, song_genreid, song_filename, song_pathid, " \
"song_number, song_disk, song_year, song_comment, song_composerid, song_length, song_bitrate, "
"song_rating, song_playcount, song_addedtime, song_lastplay, song_filesize FROM songs" ) );
query.Add( wxT( "UPDATE songs1 SET song_genre = ( SELECT genre_name FROM genres WHERE song_genreid = genre_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_composer = ( SELECT composer_name FROM composers WHERE song_composerid = composer_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_artist = ( SELECT artist_name FROM artists WHERE song_artistid = artist_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_album = ( SELECT album_name FROM albums WHERE song_albumid = album_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_path = ( SELECT path_value FROM paths WHERE song_pathid = path_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_coverid = ( SELECT album_coverid FROM albums WHERE song_albumid = album_id )" ) );
query.Add( wxT( "UPDATE songs1 SET song_offset = 0" ) );
query.Add( wxT( "DROP TABLE songs" ) );
query.Add( wxT( "ALTER TABLE songs1 RENAME TO songs" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_name on songs( song_name ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumid on songs( song_albumid,song_artist,song_year DESC, song_album, song_disk )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composerid on songs( song_composerid, song_composer )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artistid on songs( song_artistid, song_artist )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartistid on songs( song_albumartistid, song_albumartist )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genreid on songs( song_genreid, song_genre )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_pathid on songs( song_pathid ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_length on songs( song_length ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_bitrate on songs( song_bitrate ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_rating on songs( song_rating ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_playcount on songs( song_playcount ASC )" ) );
//query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime on songs( song_addedtime ASC )" ) );
//query.Add( wxT( "CREATE INDEX song_addedtime_desc ON songs( song_addedtime DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_lastplay on songs( song_lastplay ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composerid on songs( song_composerid ASC )" ) );
//query.Add( wxT( "CREATE INDEX song_composerid_desc ON songs( song_composerid DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_number ON songs( song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_path ON songs( song_path ASC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_format ON songs( song_format ASC )" ) );
//query.Add( wxT( "CREATE INDEX song_rating_desc ON songs( song_rating DESC )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genre ON songs( song_genre,song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_genre_desc ON songs( song_genre DESC,song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composer ON songs( song_composer,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_composer_desc ON songs( song_composer DESC,song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artist ON songs( song_artist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_artist_desc ON songs( song_artist DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartist ON songs( song_albumartist,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_albumartist_desc ON songs( song_albumartist DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_album ON songs( song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_album_desc ON songs( song_album DESC,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_disk ON songs( song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_disk_desc ON songs( song_disk DESC,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_year ON songs( song_year,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_year_desc ON songs( song_year DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime ON songs( song_addedtime,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime_desc ON songs( song_addedtime DESC,song_album,song_disk,song_albumid,song_number )" ) );
NeedVacuum = ( dbVer > 4 );
}
}
case 16 : // Added Album Artist to dynamic playlist
{
if( dbVer > 4 )
{
query.Add( wxT( "UPDATE playlists SET playlist_sorttype = playlist_sorttype + 1 WHERE playlist_sorttype > 1;" ) );
query.Add( wxT( "UPDATE plsets SET plset_type = plset_type + 1 WHERE plset_type > 1;" ) );
query.Add( wxT( "UPDATE plsets SET plset_option = plset_option + 1 WHERE " \
"( plset_option > 2 AND plset_type IN ( 9 ) ) OR" \
"( plset_option > 0 AND plset_type IN ( 9, 10, 11 ) );" ) );
}
}
case 17 : // Changed addedtime index to sort by album, disk, track also
{
if( dbVer > 4 )
{
query.Add( wxT( "DROP INDEX song_addedtime;" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime ON songs( song_addedtime,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_addedtime_desc ON songs( song_addedtime DESC,song_album,song_disk,song_albumid,song_number )" ) );
query.Add( wxT( "CREATE TABLE IF NOT EXISTS deleted( delete_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"delete_path VARCHAR, delete_date INTEGER );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS delete_path on deleted(delete_path ASC);" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS delete_date on deleted(delete_date ASC);" ) );
}
}
case 18 :
{
if( dbVer > 4 )
{
query.Add( wxT( "DROP INDEX song_path;" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS song_path_filename ON songs( song_path, song_filename )" ) );
query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'tag_name' on tags (tag_name ASC);" ) );
}
}
case 19 :
{
if( dbVer > 4 )
{
query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_albumsku VARCHAR" ) );
query.Add( wxT( "ALTER TABLE songs ADD COLUMN song_coverlink VARCHAR" ) );
}
}
case 20 :
{
if( dbVer > 4 )
{
query.Add( wxT( "ALTER TABLE playlists ADD COLUMN playlist_path VARCHAR" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'tag_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'playlist_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'plset_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'cover_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'audiosc_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'radiogenre_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'radiostation_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'radiolabel_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'radiosetlabel_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'podcastch_id'" ) );
query.Add( wxT( "DROP INDEX IF EXISTS 'podcastitem_id'" ) );
}
guLogMessage( wxT( "Updating database version to " GU_CURRENT_DBVERSION ) );
query.Add( wxT( "DELETE FROM Version;" ) );
query.Add( wxT( "INSERT INTO Version( version ) VALUES( " GU_CURRENT_DBVERSION " );" ) );
}
default:
break;
}
if( NeedVacuum )
{
query.Add( wxT( "VACUUM;" ) );
}
int Count = query.Count();
for( int Index = 0; Index < Count; Index++ )
{
try
{
//guLogMessage( wxT( "%s" ), query[ Index ].c_str() );
ExecuteUpdate( query[ Index ] );
}
catch( wxSQLite3Exception& e )
{
guLogError( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch( ... )
{
guLogError( wxT( "Error executing query %s" ), query[ Index ].c_str() );
}
}
return true;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetGenreId( wxString &genrename )
{
if( m_LastGenre == genrename )
{
return m_LastGenreId;
}
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
m_LastGenre = genrename;
query = wxString::Format( wxT( "SELECT song_genreid FROM songs " \
"WHERE song_genre = '%s' LIMIT 1;" ),
escape_query_str( genrename ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastGenreId = dbRes.GetInt( 0 );
}
else
{
query = wxT( "SELECT MAX(song_genreid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastGenreId = dbRes.GetInt( 0 ) + 1;
}
else
{
RetVal = m_LastGenreId = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetComposerId( wxString &composername, bool create )
{
if( m_LastComposer == composername )
{
return m_LastComposerId;
}
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
// printf( "GetArtistId\n" );
m_LastComposer = composername;
query = wxString::Format( wxT( "SELECT song_composerid FROM songs " \
"WHERE song_composer = '%s' LIMIT 1;" ),
escape_query_str( composername ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastComposerId = dbRes.GetInt( 0 );
}
else if( create )
{
query = wxT( "SELECT MAX(song_composerid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastComposerId = dbRes.GetInt( 0 ) + 1;
}
else
{
RetVal = m_LastComposerId = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxBitmap * guDbLibrary::GetCoverBitmap( const int coverid, const bool thumb )
{
if( coverid <= 0 )
return NULL;
wxImage * Img = NULL;
wxBitmap * RetVal = NULL;
wxString query;
wxSQLite3ResultSet dbRes;
const unsigned char * Data;
int DataLen = 0;
query = wxT( "SELECT " );
query += thumb ? wxT( "cover_thumb" ) : wxT( "cover_midsize" );
query += wxString::Format( wxT( " FROM covers WHERE cover_id = %u LIMIT 1;" ), coverid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
Data = dbRes.GetBlob( 0, DataLen );
if( DataLen )
{
//guLogMessage( wxT( "Read %i bytes for image %i" ), len, CoverId );
unsigned char * ImgData = ( unsigned char * ) malloc( DataLen );
memcpy( ImgData, Data, DataLen );
int ImgSize = thumb ? GUCOVER_THUMB_SIZE : GUCOVER_IMAGE_SIZE;
Img = new wxImage( ImgSize, ImgSize, ImgData );
//TmpImg->SaveFile( wxString::Format( wxT( "/home/jrios/%u.jpg" ), CoverId ), wxBITMAP_TYPE_JPEG );
RetVal = new wxBitmap( * Img );
delete Img;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::AddCoverFile( const wxString &coverfile, const wxString &coverhash )
{
wxString query;
wxSQLite3ResultSet dbRes;
int CoverId = 0;
wxString CoverFile;
//guLogMessage( wxT( "AddCoverFile( '%s', '%s' )" ), coverfile.c_str(), coverhash.c_str() );
// Create the Thumb image
wxImage TmpImg;
TmpImg.LoadFile( coverfile );
if( TmpImg.IsOk() )
{
wxString CoverHash;
if( coverhash.IsEmpty() )
{
guMD5 md5;
CoverHash = md5.MD5File( coverfile );
}
else
CoverHash = coverhash;
//guLogWarning( _T( "Scaling image %i" ), n );
TmpImg.Rescale( GUCOVER_THUMB_SIZE, GUCOVER_THUMB_SIZE, wxIMAGE_QUALITY_HIGH );
if( TmpImg.IsOk() )
{
// wxFileOutputStream FOut( wxString::Format( wxT( "/home/jrios/%s.jpg" ), coverhash.c_str() ) );
// TmpImg.SaveFile( FOut, wxBITMAP_TYPE_JPEG );
// FOut.Close();
wxImage MidImg;
MidImg.LoadFile( coverfile );
if( MidImg.IsOk() )
{
MidImg.Rescale( GUCOVER_IMAGE_SIZE, GUCOVER_IMAGE_SIZE, wxIMAGE_QUALITY_HIGH );
wxSQLite3Statement stmt = m_Db->PrepareStatement( wxString::Format( wxT( "INSERT INTO covers( cover_id, cover_path, cover_thumb, cover_midsize, cover_hash ) "
"VALUES( NULL, '%s', ?, ?, '%s' );" ), escape_query_str( coverfile ).c_str(), CoverHash.c_str() ) );
try {
stmt.Bind( 1, TmpImg.GetData(), TmpImg.GetWidth() * TmpImg.GetHeight() * 3 );
stmt.Bind( 2, MidImg.GetData(), MidImg.GetWidth() * MidImg.GetHeight() * 3 );
//guLogMessage( wxT( "AddCoverFile: %s" ), stmt.GetSQL().c_str() );
stmt.ExecuteQuery();
}
catch( wxSQLite3Exception& e )
{
guLogError( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch( ... )
{
guLogError( wxT( "Error inserting the image %s" ), coverfile.c_str() );
}
CoverId = GetLastRowId();
}
else
{
guLogError( wxT( "Error resizing to %i" ), GUCOVER_IMAGE_SIZE );
}
}
else
{
guLogError( wxT( "Error resizing to %i" ), GUCOVER_THUMB_SIZE );
}
}
else
{
guLogError( wxT( "Invalid cover file '%s'" ), coverfile.c_str() );
}
return CoverId;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::AddCoverImage( const wxImage &image )
{
//guLogMessage( wxT( "guDbLibrary::AddCoverImage" ) );
wxString query;
wxSQLite3ResultSet dbRes;
int CoverId = 0;
wxString CoverFile;
wxImage MidImg = image;
MidImg.Rescale( GUCOVER_IMAGE_SIZE, GUCOVER_IMAGE_SIZE, wxIMAGE_QUALITY_HIGH );
if( MidImg.IsOk() )
{
wxImage TinyImg = image;
TinyImg.Rescale( GUCOVER_THUMB_SIZE, GUCOVER_THUMB_SIZE, wxIMAGE_QUALITY_HIGH );
if( TinyImg.IsOk() )
{
wxSQLite3Statement stmt = m_Db->PrepareStatement( wxT( "INSERT INTO covers( cover_id, cover_path, cover_thumb, cover_midsize, cover_hash ) "
"VALUES( NULL, '', ?, ?, '' );" ) );
try {
stmt.Bind( 1, TinyImg.GetData(), TinyImg.GetWidth() * TinyImg.GetHeight() * 3 );
stmt.Bind( 2, MidImg.GetData(), MidImg.GetWidth() * MidImg.GetHeight() * 3 );
//guLogMessage( wxT( "AddCoverFile: %s" ), stmt.GetSQL().c_str() );
stmt.ExecuteQuery();
}
catch( wxSQLite3Exception& e )
{
guLogError( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch( ... )
{
guLogError( wxT( "Error inserting the image" ) );
}
CoverId = GetLastRowId();
}
else
{
guLogError( wxT( "Error resizing to %i" ), GUCOVER_THUMB_SIZE );
}
}
else
{
guLogError( wxT( "Error resizing to %i" ), GUCOVER_IMAGE_SIZE );
}
return CoverId;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateCoverFile( int coverid, const wxString &coverfile, const wxString &coverhash )
{
wxString query;
//int CoverId = 0;
wxString CoverFile;
// Create the Thumb image
wxImage TmpImg;
TmpImg.LoadFile( coverfile );
if( TmpImg.IsOk() )
{
//guLogWarning( _T( "Scaling image %i" ), n );
TmpImg.Rescale( GUCOVER_THUMB_SIZE, GUCOVER_THUMB_SIZE, wxIMAGE_QUALITY_HIGH );
if( TmpImg.IsOk() )
{
wxImage MidImg;
MidImg.LoadFile( coverfile );
MidImg.Rescale( GUCOVER_IMAGE_SIZE, GUCOVER_IMAGE_SIZE, wxIMAGE_QUALITY_HIGH );
if( MidImg.IsOk() )
{
//guLogWarning( wxT( "Cover Image w:%u h:%u " ), TmpImg.GetWidth(), TmpImg.GetHeight() );
wxSQLite3Statement stmt = m_Db->PrepareStatement( wxString::Format(
wxT( "UPDATE covers SET cover_thumb = ?, cover_midsize = ?, cover_hash = '%s' WHERE cover_id = %u;" ), coverhash.c_str(), coverid ) );
try {
stmt.Bind( 1, TmpImg.GetData(), TmpImg.GetWidth() * TmpImg.GetHeight() * 3 );
stmt.Bind( 2, MidImg.GetData(), MidImg.GetWidth() * MidImg.GetHeight() * 3 );
stmt.ExecuteQuery();
}
catch( wxSQLite3Exception& e )
{
guLogMessage( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
}
}
}
else
{
guLogError( wxT( "Invalid cover file '%s'" ), coverfile.c_str() );
}
}
//// -------------------------------------------------------------------------------- //
//int guDbLibrary::FindCoverFile( const wxString &dirname )
//{
// wxString query;
// wxSQLite3ResultSet dbRes;
// wxDir Dir;
// wxString FileName;
// wxString CurFile;
// wxString DirName = dirname;
// int CoverId = 0;
//
// if( !DirName.EndsWith( wxT( "/" ) ) )
// DirName += wxT( "/" );
//
// Dir.Open( DirName );
// //wxSetWorkingDirectory( DirName );
//
// if( Dir.IsOpened() )
// {
// if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES ) )
// {
// do {
// CurFile = FileName.Lower();
// //guLogMessage( wxT( "FindCoverFile: Found file '%s'" ), FileName.c_str() );
// if( SearchCoverWords( CurFile, m_CoverSearchWords ) )
// {
// //guLogMessage( wxT( "FindCoverFile: This file have been detected as a Cover" ) );
// if( CurFile.EndsWith( wxT( ".jpg" ) ) ||
// CurFile.EndsWith( wxT( ".jpeg" ) ) ||
// CurFile.EndsWith( wxT( ".png" ) ) ||
// CurFile.EndsWith( wxT( ".bmp" ) ) ||
// CurFile.EndsWith( wxT( ".gif" ) ) )
// {
// //guLogMessage( wxT( "FindCoverFile: This file looks like an image file" ) );
// CurFile = DirName + FileName;
// //guLogMessage( wxT( "Found Cover: %s" ), CurFile.c_str() );
// guMD5 md5;
// wxString CoverHash = md5.MD5File( CurFile );
//
// escape_query_str( &CurFile );
//
// query = wxString::Format( wxT( "SELECT cover_id, cover_path, cover_hash FROM covers ""WHERE cover_path = '%s' LIMIT 1;" ), CurFile.c_str() );
//
// dbRes = ExecuteQuery( query );
//
// if( dbRes.NextRow() ) // The cover is found in the database
// {
// CoverId = dbRes.GetInt( 0 );
// // Check if the file have been changed
// if( dbRes.GetString( 2 ) != CoverHash )
// {
// // The cover is different. Update the thumb is needed
// UpdateCoverFile( CoverId, DirName + FileName, CoverHash );
// }
// }
// else
// {
// CoverId = AddCoverFile( DirName + FileName, CoverHash );
// }
// break;
// }
// }
// } while( Dir.GetNext( &FileName ) );
// }
// }
// //wxSetWorkingDirectory( SavedDir );
// return CoverId;
//}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::GetCoverPath( const int CoverId )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString RetVal = wxEmptyString;
if( m_LastCoverId != CoverId )
{
int count = m_LastItems.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( m_LastItems[ index ].m_Id == CoverId )
{
m_LastCoverId = CoverId;
m_LastCoverPath = m_LastItems[ index ].m_Name;
return m_LastCoverPath;
}
}
}
if( count > 25 ) // MAX_CACHE_ITEMS
{
m_LastItems.RemoveAt( 0 );
}
query = wxString::Format( wxT( "SELECT cover_path, cover_hash FROM covers " \
"WHERE cover_id = %u " \
"LIMIT 1;" ), CoverId );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetString( 0 );
if( !RetVal.IsEmpty() )
{
// Check if the cover have been updated
guMD5 md5;
wxString CoverHash = md5.MD5File( RetVal );
if( CoverHash != dbRes.GetString( 1 ) )
{
UpdateCoverFile( CoverId, RetVal, CoverHash );
}
}
}
m_LastCoverId = CoverId;
m_LastCoverPath = RetVal;
m_LastItems.Add( new guListItem( CoverId, m_LastCoverPath ) );
dbRes.Finalize();
}
else
RetVal = m_LastCoverPath;
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::SetAlbumCover( const int AlbumId, const wxImage &image )
{
int CoverId = 0;
wxSQLite3ResultSet dbRes;
wxString query;
wxString FileName;
int RetVal = 0;
CoverId = GetAlbumCoverId( AlbumId );
if( CoverId > 0 )
{
query = wxString::Format( wxT( "DELETE FROM covers WHERE cover_id = %i;" ), CoverId );
ExecuteUpdate( query );
}
if( image.IsOk() )
{
CoverId = AddCoverImage( image );
query = wxString::Format( wxT( "UPDATE songs SET song_coverid = %i WHERE song_albumid = %i;" ), CoverId, AlbumId );
RetVal = ExecuteUpdate( query );
}
else
{
query = wxString::Format( wxT( "UPDATE songs SET song_coverid = 0 WHERE song_albumid = %i;" ), AlbumId );
//guLogMessage( query );
CoverId = 0;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::SetAlbumCover( const int AlbumId, const wxString &CoverPath, const wxString &coverhash )
{
int CoverId = 0;
wxSQLite3ResultSet dbRes;
wxString query;
wxString FileName;
int RetVal = 0;
//guLogMessage( wxT( "Updating album: %i path: '%s'" ), AlbumId, CoverPath.c_str() );
// Delete the actual assigned Cover
// Find the Cover assigned to the album
CoverId = GetAlbumCoverId( AlbumId );
if( CoverId > 0 )
{
query = wxString::Format( wxT( "DELETE FROM covers WHERE cover_id = %i;" ), CoverId );
ExecuteUpdate( query );
}
if( !CoverPath.IsEmpty() )
{
//guLogMessage( wxT( "Setting new cover '%s'" ), CoverPath.c_str() );
CoverId = AddCoverFile( CoverPath, coverhash );
query = wxString::Format( wxT( "UPDATE songs SET song_coverid = %i WHERE song_albumid = %i;" ), CoverId, AlbumId );
RetVal = ExecuteUpdate( query );
}
else
{
query = wxString::Format( wxT( "UPDATE songs SET song_coverid = 0 WHERE song_albumid = %i;" ), AlbumId );
ExecuteUpdate( query );
CoverId = 0;
}
// // Update the AlbumsCache
// guAlbumItem * AlbumItem = guAlbumItemGetItem( m_AlbumsCache, AlbumId );
// if( AlbumItem )
// {
// AlbumItem->m_CoverId = CoverId;
// AlbumItem->m_CoverPath = CoverPath;
// //guLogMessage( wxT( "Updated Album with Cover %i '%s'" ), CoverId, CoverPath.c_str() );
// }
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumId( wxString &albumname, const int artistid, const int pathid,
const wxString &pathname, const int coverid )
{
//guLogMessage( wxT( "GetAlbumId : %s" ), m_LastAlbum.c_str() );
if( m_LastAlbum == albumname )
{
//guLogMessage( wxT( "Album was found in cache" ) );
return m_LastAlbumId;
}
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
query = wxString::Format( wxT( "SELECT song_albumid, song_artistid " \
"FROM songs " \
"WHERE song_album = '%s' " \
"AND song_pathid = %u LIMIT 1;" ),
escape_query_str( albumname ).c_str(), pathid );
//guLogMessage( wxT( "%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastAlbumId = dbRes.GetInt( 0 );
// // Now check if the artist id changed and if so update it
// if( dbRes.GetInt( 1 ) != artistid )
// {
// query = wxString::Format( wxT( "UPDATE songs SET song_artistid = %u "
// "WHERE album_id = %i;" ), artistid, RetVal );
// ExecuteUpdate( query );
// }
}
else
{
query = wxT( "SELECT MAX(song_albumid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastAlbumId = dbRes.GetInt( 0 ) + 1;
}
else
{
RetVal = m_LastAlbumId = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayInt guDbLibrary::GetLabelIds( const wxArrayString &Labels )
{
wxArrayInt RetVal;
wxString LabelName;
int LabelId;
int count = Labels.Count();
for( int index = 0; index < count; index++ )
{
LabelName = Labels[ index ];
if( GetLabelId( &LabelId, LabelName ) )
RetVal.Add( LabelId );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetLabelId( int * LabelId, wxString &LabelName )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
// printf( "GetLabelId\n" );
escape_query_str( &LabelName );
query = wxString::Format( wxT( "SELECT tag_id FROM tags " \
"WHERE tag_name = '%s' LIMIT 1;" ), LabelName.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
* LabelId = dbRes.GetInt( 0 );
RetVal = 1;
}
else
{
query = wxT( "INSERT INTO tags( tag_id, tag_name ) VALUES( NULL, '" ) +
LabelName + wxT( "');" );
if( ExecuteUpdate( query ) == 1 )
{
* LabelId = GetLastRowId();
RetVal = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::PathExists( const wxString &path )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
wxString PathValue = path;
if( !PathValue.EndsWith( wxT( "/" ) ) )
PathValue += '/';
escape_query_str( &PathValue );
query = wxString::Format( wxT( "SELECT song_pathid FROM songs WHERE song_path = '%s' LIMIT 1;" ),
PathValue.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPathId( wxString &PathValue )
{
if( PathValue == m_LastPath )
{
return m_LastPathId;
}
int RetVal = 0;
//TODO Add a Lock
wxString query;
wxSQLite3ResultSet dbRes;
m_LastPath = PathValue;
if( !PathValue.EndsWith( wxT( "/" ) ) )
PathValue += '/';
query = wxString::Format( wxT( "SELECT song_pathid FROM songs " \
"WHERE song_path = '%s' LIMIT 1" ),
escape_query_str( PathValue ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastPathId = dbRes.GetInt( 0 );
}
else
{
dbRes.Finalize();
query = wxT( "SELECT MAX(song_pathid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = m_LastPathId = dbRes.GetInt( 0 ) + 1;
}
else
{
RetVal = m_LastPathId = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongId( wxString &filename, const int pathid, const time_t filedate, const int start, bool * created )
{
//wxSQLite3StatementBuffer query;
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
// printf( "GetSongId0\n" );
// printf( "%u : %s\n", FileName.Length(), TextBuf );
query = query.Format( wxT( "SELECT song_id FROM songs WHERE song_pathid = %u " \
"AND song_filename = '%s' AND song_offset = %i LIMIT 1;" ),
pathid, escape_query_str( filename ).c_str(), start );
//printf( query.ToAscii() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
else
{
query = query.Format( wxT( "INSERT INTO songs( song_id, song_pathid, song_rating, song_playcount, song_addedtime ) " \
"VALUES( NULL, %u, -1, 0, %lu )" ), pathid, filedate );
//guLogMessage( wxT( "Query: '%s'" ), query.c_str() );
if( ExecuteUpdate( query ) )
{
RetVal = GetLastRowId();
}
if( created )
{
* created = true;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongId( wxString &FileName, wxString &FilePath, const time_t filedate, const int start, bool * created )
{
return GetSongId( FileName, GetPathId( FilePath ), filedate, start, created );
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::ReadFileTags( const wxString &filename, const bool allowrating )
{
if( guCuePlaylistFile::IsValidFile( filename ) ) // If its a cue playlist
{
//guLogMessage( wxT( "***** CUE FILE ***** '%s'" ), filename.c_str() );
//
guCuePlaylistFile CuePlaylistFile( filename );
int Count = CuePlaylistFile.Count();
if( Count )
{
//guLogMessage( wxT( "With %i tracks" ), Count );
for( int Index = 0; Index < Count; Index++ )
{
guCuePlaylistItem &CueItem = CuePlaylistFile.GetItem( Index );
//guLogMessage( wxT( "Loading track %i '%s'" ), Index, CueItem.m_TrackPath.c_str() );
if( wxFileExists( CueItem.m_TrackPath ) )
{
wxString query = wxT( "DELETE FROM songs WHERE song_filename = '" );
query += escape_query_str( CueItem.m_TrackPath.AfterLast( wxT( '/' ) ) );
query += wxT( "' AND song_path = '");
query += escape_query_str( wxPathOnly( CueItem.m_TrackPath ) + wxT( "/" ) );
query += wxT( "' AND song_offset = 0" );
ExecuteUpdate( query );
guTagInfo * TagInfo = guGetTagInfoHandler( CueItem.m_TrackPath );
if( TagInfo )
{
if( TagInfo->Read() )
{
guTrack CurTrack;
CurTrack.m_Path = wxPathOnly( CueItem.m_TrackPath ) + wxT( "/" );
CurTrack.m_GenreName = CueItem.m_Genre;
CurTrack.m_SongName = CueItem.m_Name;
CurTrack.m_ArtistName = CueItem.m_ArtistName;
CurTrack.m_AlbumArtist = CueItem.m_AlbumArtist;
CurTrack.m_Composer = CueItem.m_Composer;
CurTrack.m_Comments = CueItem.m_Comment;
CurTrack.m_AlbumName = CueItem.m_AlbumName;
CurTrack.m_Offset = CueItem.m_Start;
CurTrack.m_Length = CueItem.m_Length;
CurTrack.m_FileName = CueItem.m_TrackPath.AfterLast( wxT( '/' ) );
CurTrack.m_Number = Index + 1;
long Year;
if( CueItem.m_Year.ToLong( &Year ) )
CurTrack.m_Year = Year;
CurTrack.m_Bitrate = TagInfo->m_Bitrate;
//
//
//
CurTrack.m_PathId = GetPathId( CurTrack.m_Path );
CurTrack.m_ComposerId = GetComposerId( CurTrack.m_Composer );
if( CurTrack.m_ArtistName.IsEmpty() )
CurTrack.m_ArtistName = _( "Unknown" );
CurTrack.m_ArtistId = GetArtistId( CurTrack.m_ArtistName );
CurTrack.m_AlbumArtistId = GetAlbumArtistId( CurTrack.m_AlbumArtist );
if( CurTrack.m_AlbumName.IsEmpty() && !CurTrack.m_Path.IsEmpty() )
CurTrack.m_AlbumName = CurTrack.m_Path.BeforeLast( wxT( '/' ) ).AfterLast( wxT( '/' ) );
CurTrack.m_AlbumId = GetAlbumId( CurTrack.m_AlbumName, CurTrack.m_ArtistId, CurTrack.m_PathId, CurTrack.m_Path );
CurTrack.m_CoverId = GetAlbumCoverId( CurTrack.m_AlbumId );
if( CurTrack.m_GenreName.IsEmpty() )
CurTrack.m_GenreName = _( "Unknown" );
CurTrack.m_GenreId = GetGenreId( CurTrack.m_GenreName );
if( TagInfo->m_Length )
{
CurTrack.m_FileSize = ( guGetFileSize( CueItem.m_TrackPath ) * CueItem.m_Length ) / TagInfo->m_Length;
}
else
{
CurTrack.m_FileSize = 0;
}
if( CurTrack.m_SongName.IsEmpty() )
CurTrack.m_SongName = CurTrack.m_FileName.AfterLast( wxT( '/' ) ).BeforeLast( wxT( '.' ) );
bool IsNewTrack = false;
CurTrack.m_SongId = GetSongId( CurTrack.m_FileName, CurTrack.m_PathId,
GetFileLastChangeTime( filename ), CurTrack.m_Offset, &IsNewTrack );
UpdateSong( CurTrack, IsNewTrack || allowrating );
}
else
{
guLogError( wxT( "Cant read tags from '%s'" ), filename.c_str() );
}
delete TagInfo;
}
}
}
return 1;
}
}
else
{
guTagInfo * TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
guTrack CurTrack;
//guLogMessage( wxT( "FileName: '%s'" ), filename.c_str() );
CurTrack.m_Path = wxPathOnly( filename );
if( !CurTrack.m_Path.EndsWith( wxT( "/" ) ) )
CurTrack.m_Path += '/';
//guLogMessage( wxT( "PathName: %s" ), m_Path.c_str() );
if( TagInfo->Read() )
{
CurTrack.m_Composer = TagInfo->m_Composer;
CurTrack.m_ArtistName = TagInfo->m_ArtistName;
CurTrack.m_AlbumArtist = TagInfo->m_AlbumArtist;
CurTrack.m_AlbumName = TagInfo->m_AlbumName;
CurTrack.m_GenreName = TagInfo->m_GenreName;
CurTrack.m_SongName = TagInfo->m_TrackName;
CurTrack.m_Number = TagInfo->m_Track;
CurTrack.m_Year = TagInfo->m_Year;
CurTrack.m_Length = TagInfo->m_Length;
CurTrack.m_Bitrate = TagInfo->m_Bitrate;
CurTrack.m_Comments = TagInfo->m_Comments;
CurTrack.m_Disk = TagInfo->m_Disk;
CurTrack.m_Rating = TagInfo->m_Rating;
CurTrack.m_PlayCount = TagInfo->m_PlayCount;
}
else
{
guLogError( wxT( "Cant read tags from '%s'" ), filename.c_str() );
}
CurTrack.m_PathId = GetPathId( CurTrack.m_Path );
CurTrack.m_ComposerId = GetComposerId( CurTrack.m_Composer );
if( CurTrack.m_ArtistName.IsEmpty() )
CurTrack.m_ArtistName = _( "Unknown" );
CurTrack.m_ArtistId = GetArtistId( CurTrack.m_ArtistName );
CurTrack.m_AlbumArtistId = GetAlbumArtistId( CurTrack.m_AlbumArtist );
if( CurTrack.m_AlbumName.IsEmpty() && !CurTrack.m_Path.IsEmpty() )
CurTrack.m_AlbumName = CurTrack.m_Path.BeforeLast( wxT( '/' ) ).AfterLast( wxT( '/' ) );
CurTrack.m_AlbumId = GetAlbumId( CurTrack.m_AlbumName, CurTrack.m_ArtistId, CurTrack.m_PathId, CurTrack.m_Path );
CurTrack.m_CoverId = GetAlbumCoverId( CurTrack.m_AlbumId );
if( CurTrack.m_GenreName.IsEmpty() )
CurTrack.m_GenreName = _( "Unknown" );
CurTrack.m_GenreId = GetGenreId( CurTrack.m_GenreName );
CurTrack.m_FileName = filename.AfterLast( wxT( '/' ) );
CurTrack.m_FileSize = guGetFileSize( filename );
if( CurTrack.m_SongName.IsEmpty() )
CurTrack.m_SongName = CurTrack.m_FileName.AfterLast( wxT( '/' ) ).BeforeLast( wxT( '.' ) );
bool IsNewTrack = false;
CurTrack.m_SongId = GetSongId( CurTrack.m_FileName, CurTrack.m_PathId,
GetFileLastChangeTime( filename ), CurTrack.m_Offset, &IsNewTrack );
wxArrayInt ArrayIds;
//
if( TagInfo->m_TrackLabels.Count() )
{
ArrayIds.Add( CurTrack.m_SongId );
wxArrayInt TrackLabelIds = GetLabelIds( TagInfo->m_TrackLabels );
SetSongsLabels( ArrayIds, TrackLabelIds );
}
if( TagInfo->m_ArtistLabels.Count() )
{
ArrayIds.Empty();
ArrayIds.Add( CurTrack.m_ArtistId );
wxArrayInt ArtistLabelIds = GetLabelIds( TagInfo->m_ArtistLabels );
SetArtistsLabels( ArrayIds, ArtistLabelIds );
}
if( TagInfo->m_AlbumLabels.Count() )
{
ArrayIds.Empty();
ArrayIds.Add( CurTrack.m_AlbumId );
wxArrayInt AlbumLabelIds = GetLabelIds( TagInfo->m_AlbumLabels );
SetAlbumsLabels( ArrayIds, AlbumLabelIds );
}
UpdateSong( CurTrack, IsNewTrack || allowrating );
delete TagInfo;
return 1;
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::AddFiles( const wxArrayString &files )
{
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
ReadFileTags( files[ Index ] );
}
return Count;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateTrackLength( const int trackid, const int length )
{
wxString query = wxString::Format( wxT( "UPDATE songs SET song_length = %i " \
"WHERE song_id = %i" ), length, trackid );
ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateTrackBitRate( const int trackid, const int bitrate )
{
wxString query = wxString::Format( wxT( "UPDATE songs SET song_bitrate = %i " \
"WHERE song_id = %i" ), bitrate, trackid );
ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateSongs( const guTrackArray * Songs, const wxArrayInt &changedflags )
{
guTrack * Song;
int count = Songs->Count();
wxArrayPtrVoid MediaViewerPtrs;
// Process each Track
for( int index = 0; index < count; index++ )
{
if( !( changedflags[ index ] & ( guTRACK_CHANGED_DATA_TAGS | guTRACK_CHANGED_DATA_RATING ) ) )
continue;
Song = &( * Songs )[ index ];
if( Song->m_Type == guTRACK_TYPE_DB )
{
if( Song->m_MediaViewer )
{
if( MediaViewerPtrs.Index( Song->m_MediaViewer ) == wxNOT_FOUND )
MediaViewerPtrs.Add( Song->m_MediaViewer );
}
//
// Update the Library
//
wxString PathName;
int PathId;
int AlbumArtistId;
int ArtistId;
int ComposerId;
int AlbumId;
//int CoverId;
int GenreId;
//int SongId;
//wxString FileName;
PathName = wxPathOnly( Song->m_FileName ) + wxT( '/' );
//wxSetWorkingDirectory( PathName );
PathId = GetPathId( PathName );
AlbumArtistId = GetAlbumArtistId( Song->m_AlbumArtist );
ArtistId = GetArtistId( Song->m_ArtistName );
ComposerId = GetComposerId( Song->m_Composer );
AlbumId = GetAlbumId( Song->m_AlbumName, ArtistId, PathId, PathName, Song->m_CoverId );
GenreId = GetGenreId( Song->m_GenreName );
//FileName = Song->FileName.AfterLast( '/' );
//printf( ( wxT( "FileName: " ) + CurSong.FileName ).ToAscii() ); printf( "\n" );
//GetSongId( &SongId, FileName, PathId );
guTrack CurTrack = * Song;
CurTrack.m_GenreId = GenreId;
CurTrack.m_ArtistId = ArtistId;
CurTrack.m_AlbumArtistId = AlbumArtistId;
CurTrack.m_ComposerId = ComposerId;
CurTrack.m_AlbumId = AlbumId;
CurTrack.m_PathId = PathId;
CurTrack.m_FileName = Song->m_FileName.AfterLast( '/' );
//CurSong.SongId = SongId;
//CurSong.FileName.c_str(),
//CurSong.Number
//CurSong.Year,
//CurSong.Length,
UpdateSong( CurTrack, true );
}
}
// We added in PanelPtr all panels we are updating tracks
// And send the clean db event to all of them
wxCommandEvent event( wxEVT_MENU, ID_LIBRARY_DOCLEANDB );
count = MediaViewerPtrs.Count();
for( int index = 0; index < count; index++ )
{
// event.SetClientData( ( void * ) MediaViewerPtrs[ index ] );
wxPostEvent( ( guMediaViewer * ) MediaViewerPtrs[ index ], event );
}
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::UpdateSong( const guTrack &track, const bool allowrating )
{
wxString query;
query = wxString::Format( wxT( "UPDATE songs SET song_name = '%s', " \
"song_genreid = %u, song_genre = '%s', " \
"song_artistid = %u, song_artist = '%s', " \
"song_albumartistid = %u, song_albumartist = '%s', " \
"song_albumid = %u, song_album = '%s', " \
"song_pathid = %u, song_path = '%s', " \
"song_filename = '%s', song_format = '%s', " \
"song_number = %u, song_year = %u, " \
"song_composerid = %u, song_composer = '%s', " \
"song_comment = '%s', song_coverid = %i, song_disk = '%s', " \
"song_length = %u, song_offset = %u, song_bitrate = %u, " \
"song_filesize = %u" ),
escape_query_str( track.m_SongName ).c_str(),
track.m_GenreId,
escape_query_str( track.m_GenreName ).c_str(),
track.m_ArtistId,
escape_query_str( track.m_ArtistName ).c_str(),
track.m_AlbumArtistId,
escape_query_str( track.m_AlbumArtist ).c_str(),
track.m_AlbumId,
escape_query_str( track.m_AlbumName ).c_str(),
track.m_PathId,
escape_query_str( track.m_Path ).c_str(),
escape_query_str( track.m_FileName ).c_str(),
escape_query_str( track.m_FileName.AfterLast( '.' ) ).c_str(),
track.m_Number,
track.m_Year,
track.m_ComposerId, //escape_query_str( track.m_Composer ).c_str(),
escape_query_str( track.m_Composer ).c_str(),
escape_query_str( track.m_Comments ).c_str(),
track.m_CoverId,
escape_query_str( track.m_Disk ).c_str(),
track.m_Length,
track.m_Offset,
track.m_Bitrate,
track.m_FileSize );
if( allowrating )
{
query += wxString::Format( wxT( ", song_rating = %i, song_playcount = %i " ),
track.m_Rating,
track.m_PlayCount );
}
query += wxString::Format( wxT( " WHERE song_id = %u;" ), track.m_SongId );
return ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateImageFile( const char * filename, const char * saveto, const wxBitmapType type, const int maxsize )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString FileName;
int AlbumId;
int CoverId;
wxString CoverHash;
wxString CoverFile = FileName = wxString( filename, wxConvUTF8 );
wxString SaveTo = wxString( saveto, wxConvUTF8 );
if( FileName.IsEmpty() )
return;
if( guIsValidAudioFile( FileName ) )
{
//guLogMessage( wxT( "Trying to get image from file '%s'" ), FileName.c_str() );
wxImage * Image = guTagGetPicture( FileName );
if( Image )
{
if( !Image->IsOk() )
{
delete Image;
return;
}
if( maxsize )
{
Image->Rescale( maxsize, maxsize, wxIMAGE_QUALITY_HIGH );
}
CoverFile = wxPathOnly( FileName ) + wxT( '/' ) + SaveTo;
if( !Image->SaveFile( CoverFile, type ) )
{
delete Image;
return;
}
FileName = CoverFile;
delete Image;
}
else
{
return;
}
}
guMD5 md5;
wxString NewCoverHash = md5.MD5File( FileName );
escape_query_str( &CoverFile );
query = wxT( "SELECT cover_id, cover_hash FROM covers WHERE cover_path = '" ) + CoverFile +
wxT( "' LIMIT 1;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
CoverId = dbRes.GetInt( 0 );
CoverHash = dbRes.GetString( 1 );
dbRes.Finalize();
if( NewCoverHash != CoverHash )
{
UpdateCoverFile( CoverId, FileName, NewCoverHash );
}
return;
}
dbRes.Finalize();
// No Cover was found with this PathName
wxString Path = wxPathOnly( FileName ) + wxT( '/' );
escape_query_str( &Path );
// Now try to search the album in this path
query = wxString::Format( wxT( "SELECT song_albumid FROM songs WHERE song_path = '%s' LIMIT 1" ), Path.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
AlbumId = dbRes.GetInt( 0 );
dbRes.Finalize();
SetAlbumCover( AlbumId, FileName, NewCoverHash );
return;
}
//An image which appear to not be to any album was found. We do nothing with this
// else
// {
// guLogError( wxT( "The image '%s' with no album set" ), FileName.c_str() );
// }
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetFiltersCount() const
{
return m_TeFilters.Count() || m_GeFilters.Count() ||
m_LaFilters.Count() || m_ArFilters.Count() ||
m_AAFilters.Count() || m_CoFilters.Count() ||
m_AlFilters.Count() || m_YeFilters.Count() ||
m_RaFilters.Count() || m_PcFilters.Count();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetTeFilters( const wxArrayString &NewTeFilters, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetTeFilters %i" ), NewTeFilters.Count() );
m_TeFilters = NewTeFilters;
if( locked )
return;
m_LaFilters.Empty();
m_GeFilters.Empty();
m_AAFilters.Empty();
m_ArFilters.Empty();
m_CoFilters.Empty();
m_AlFilters.Empty();
m_YeFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetLaFilters( const wxArrayInt &NewLaFilters, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetTaFilters %i" ), NewTaFilters.Count() );
if( NewLaFilters.Index( 0 ) != wxNOT_FOUND )
{
m_LaFilters.Empty();
}
else
{
m_LaFilters = NewLaFilters;
}
if( locked )
return;
m_GeFilters.Empty();
m_AAFilters.Empty();
m_ArFilters.Empty();
m_CoFilters.Empty();
m_AlFilters.Empty();
m_YeFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetGeFilters( const wxArrayInt &NewGeFilters, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetGeFilters %i" ), NewGeFilters.Count() );
if( NewGeFilters.Index( 0 ) != wxNOT_FOUND )
{
m_GeFilters.Empty();
}
else
{
m_GeFilters = NewGeFilters;
}
if( locked )
return;
m_AAFilters.Empty();
m_ArFilters.Empty();
m_CoFilters.Empty();
m_AlFilters.Empty();
m_YeFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetArFilters( const wxArrayInt &NewArFilters, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetArFilters %i" ), NewArFilters.Count() );
if( NewArFilters.Index( 0 ) != wxNOT_FOUND )
{
m_ArFilters.Empty();
}
else
{
m_ArFilters = NewArFilters;
}
if( locked )
return;
m_YeFilters.Empty();
m_AlFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetCoFilters( const wxArrayInt &filter, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetCoFilters %i" ), filter.Count() );
if( filter.Index( 0 ) != wxNOT_FOUND )
{
m_CoFilters.Empty();
}
else
{
m_CoFilters = filter;
}
if( locked )
return;
m_AAFilters.Empty();
m_ArFilters.Empty();
m_YeFilters.Empty();
m_AlFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetAAFilters( const wxArrayInt &filter, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetAAFilters %i" ), filter.Count() );
if( filter.Index( 0 ) != wxNOT_FOUND )
{
m_AAFilters.Empty();
}
else
{
m_AAFilters = filter;
}
if( locked )
return;
m_ArFilters.Empty();
m_YeFilters.Empty();
m_AlFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetYeFilters( const wxArrayInt &filter, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetYeFilters %i" ), filter.Count() );
if( filter.Index( 0 ) != wxNOT_FOUND )
{
m_YeFilters.Empty();
}
else
{
m_YeFilters = filter;
}
if( locked )
return;
m_AlFilters.Empty();
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetAlFilters( const wxArrayInt &NewAlFilters, const bool locked )
{
//guLogMessage( wxT( "guDbLibrary::SetAlFilters %i" ), NewAlFilters.Count() );
// if( locked )
// return;
if( NewAlFilters.Index( 0 ) != wxNOT_FOUND )
{
m_AlFilters.Empty();
}
else
{
m_AlFilters = NewAlFilters;
}
if( locked )
return;
m_RaFilters.Empty();
m_PcFilters.Empty();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetRaFilters( const wxArrayInt &filter )
{
//guLogMessage( wxT( "guDbLibrary::SetYeFilters %i" ), filter.Count() );
if( filter.Index( 0 ) != wxNOT_FOUND )
{
m_RaFilters.Empty();
}
else
{
//m_RaFilters = filter;
m_RaFilters.Empty();
int Count = filter.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_RaFilters.Add( filter[ Index ] - 1 );
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetPcFilters( const wxArrayInt &filter )
{
//guLogMessage( wxT( "guDbLibrary::SetYeFilters %i" ), filter.Count() );
if( filter.Index( 0 ) != wxNOT_FOUND )
{
m_PcFilters.Empty();
}
else
{
m_PcFilters.Empty();
int Count = filter.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_PcFilters.Add( filter[ Index ] - 1 );
}
}
}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::FiltersSQL( int Level )
{
wxString subquery;
wxString query;
wxString RetVal = wxEmptyString;
if( m_TeFilters.Count() )
{
RetVal += TextFilterToSQL( m_TeFilters );
}
if( Level > guLIBRARY_FILTER_LABELS )
{
if( m_LaFilters.Count() )
{
if( !RetVal.IsEmpty() )
RetVal += wxT( " AND " );
RetVal += LabelFilterToSQL( m_LaFilters );
}
if( Level > guLIBRARY_FILTER_GENRES )
{
if( m_GeFilters.Count() )
{
if( !RetVal.IsEmpty() )
RetVal += wxT( " AND " );
RetVal += ArrayToFilter( m_GeFilters, wxT( "song_genreid" ) );
}
if( Level > guLIBRARY_FILTER_COMPOSERS )
{
if( m_CoFilters.Count() )
{
if( !RetVal.IsEmpty() )
{
RetVal += wxT( " AND " );
}
RetVal += ArrayToFilter( m_CoFilters, wxT( "song_composerid" ) );
}
if( Level > guLIBRARY_FILTER_ALBUMARTISTS )
{
if( m_AAFilters.Count() )
{
if( !RetVal.IsEmpty() )
RetVal += wxT( " AND " );
RetVal += ArrayToFilter( m_AAFilters, wxT( "song_albumartistid" ) );
}
if( Level > guLIBRARY_FILTER_ARTISTS )
{
if( m_ArFilters.Count() )
{
if( !RetVal.IsEmpty() )
RetVal += wxT( " AND " );
RetVal += ArrayToFilter( m_ArFilters, wxT( "song_artistid" ) );
}
if( Level > guLIBRARY_FILTER_YEARS )
{
if( m_YeFilters.Count() )
{
if( !RetVal.IsEmpty() )
{
RetVal += wxT( " AND " );
}
RetVal += ArrayToFilter( m_YeFilters, wxT( "song_year" ) );
}
if( Level > guLIBRARY_FILTER_ALBUMS )
{
if( m_AlFilters.Count() )
{
if( !RetVal.IsEmpty() )
RetVal += wxT( " AND " );
RetVal += ArrayToFilter( m_AlFilters, wxT( "song_albumid" ) );
}
if( Level >= guLIBRARY_FILTER_SONGS )
{
if( m_RaFilters.Count() )
{
if( !RetVal.IsEmpty() )
{
RetVal += wxT( " AND " );
}
RetVal += ArrayToFilter( m_RaFilters, wxT( "song_rating" ) );
}
if( m_PcFilters.Count() )
{
if( !RetVal.IsEmpty() )
{
RetVal += wxT( " AND " );
}
RetVal += ArrayToFilter( m_PcFilters, wxT( "song_playcount" ) );
}
}
}
}
}
}
}
}
}
//guLogMessage( wxT( "FilterSQL: '%s'" ), RetVal.c_str() );
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::AddLabel( wxString LabelName )
{
wxString query;
escape_query_str( &LabelName );
query = wxT( "INSERT INTO tags( tag_id, tag_name ) VALUES( NULL, '" ) +
LabelName + wxT( "');" );
if( ExecuteUpdate( query ) == 1 )
{
return GetLastRowId();
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::SetLabelName( const int labelid, const wxString &oldlabel, const wxString &newlabel )
{
wxString query;
if( m_MediaViewer->GetEmbeddMetadata() )
{
guTrackArray Tracks;
wxArrayInt Labels;
Labels.Add( labelid );
GetLabelsSongs( Labels, &Tracks );
UpdateSongsLabel( Tracks, oldlabel, newlabel );
}
wxString LabelName = newlabel;
escape_query_str( &LabelName );
query = query.Format( wxT( "UPDATE tags SET tag_name = '%s' WHERE tag_id = %u;" ), LabelName.c_str(), labelid );
if( ExecuteUpdate( query ) == 1 )
{
return GetLastRowId();
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::DelLabel( const int LabelId )
{
wxString query;
if( m_MediaViewer->GetEmbeddMetadata() )
{
guListItems LaItems;
guTrackArray Tracks;
wxArrayInt Labels;
Labels.Add( LabelId );
GetLabels( &LaItems, true );
GetLabelsSongs( Labels, &Tracks );
UpdateSongsLabel( Tracks, guListItemsGetName( LaItems, LabelId ), wxEmptyString );
}
query = query.Format( wxT( "DELETE FROM tags WHERE tag_id = %u;" ), LabelId );
if( ExecuteUpdate( query ) )
{
query = query.Format( wxT( "DELETE FROM settags WHERE settag_tagid = %u;" ), LabelId );
if( ExecuteUpdate( query ) )
return 1;
}
return 0;
}
// -------------------------------------------------------------------------------- //
wxArrayInt guDbLibrary::GetLabels( void )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxArrayInt RetVal;
query = wxT( "SELECT tag_id FROM tags ORDER BY tag_id;" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
RetVal.Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetLabels( guListItems * Labels, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
// guListItems RetVal;
//guLogMessage( wxT( "guDbLibrary::GetLabels" ) );
query = wxT( "SELECT tag_id, tag_name FROM tags ORDER BY " );
query += FullList ? wxT( "tag_id;" ) : wxT( "tag_name;" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Labels->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
// return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetGenres( guListItems * Genres, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
//guLogMessage( wxT( "guDbLibrary::GetGenres" ) );
//if( !GetFiltersCount() )
if( FullList )
{
query = wxT( "SELECT song_genreid, song_genre FROM songs GROUP BY song_genreid" );
}
else if( !( m_TeFilters.Count() || m_LaFilters.Count() ) )
{
query = wxT( "SELECT song_genreid, song_genre FROM songs GROUP BY song_genreid ORDER BY song_genre" );
}
else
{
query = wxT( "SELECT song_genreid, song_genre FROM songs " );
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_GENRES );
query += wxT( " GROUP BY song_genreid ORDER BY song_genre" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Genres->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetArtists( guListItems * Artists, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
//guLogMessage( wxT( "guDbLibrary::GetArtists" ) );
// guListItems RetVal;
if( FullList )
{
query = wxT( "SELECT song_artistid, song_artist FROM songs GROUP BY song_artistid;" );
}
else if( !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() || m_AAFilters.Count() || m_CoFilters.Count() ) )
{
query = wxT( "SELECT song_artistid, song_artist FROM songs GROUP BY song_artistid ORDER BY song_artist" );
}
else
{
query = wxT( "SELECT song_artistid, song_artist FROM songs " );
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_ARTISTS );
query += wxT( " GROUP BY song_artistid ORDER BY song_artist" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Artists->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
// return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetYears( guListItems * Years, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( FullList || !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ||
m_AAFilters.Count() || m_ArFilters.Count() || m_CoFilters.Count() ) )
{
query = wxT( "SELECT DISTINCT song_year FROM songs WHERE song_year > 0 ORDER BY song_year DESC;" );
}
else
{
query = wxT( "SELECT DISTINCT song_year FROM songs WHERE song_year > 0 AND " ) +
FiltersSQL( guLIBRARY_FILTER_YEARS );
query += wxT( " ORDER BY song_year DESC;" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
int Year = dbRes.GetInt( 0 );
Years->Add( new guListItem( Year, wxString::Format( wxT( "%i" ), Year ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetRatings( guListItems * Ratings, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( FullList || !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ||
m_AAFilters.Count() || m_ArFilters.Count() || m_CoFilters.Count() ||
m_YeFilters.Count() ) )
{
query = wxT( "SELECT DISTINCT song_rating FROM songs WHERE song_rating >= 0 ORDER BY song_rating DESC;" );
}
else
{
query = wxT( "SELECT DISTINCT song_rating FROM songs " ) \
wxT( "WHERE song_rating >= 0 AND " ) + FiltersSQL( guLIBRARY_FILTER_RATINGS );
query += wxT( " ORDER BY song_rating DESC;" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
int Rating = dbRes.GetInt( 0 );
// To avoid using the 0 as 0 is used for All
Ratings->Add( new guListItem( Rating + 1, wxString::Format( wxT( "%i" ), Rating ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPlayCounts( guListItems * PlayCounts, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( FullList || !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ||
m_AAFilters.Count() || m_ArFilters.Count() || m_CoFilters.Count() ||
m_YeFilters.Count() ) )
{
query = wxT( "SELECT DISTINCT song_playcount FROM songs ORDER BY song_playcount;" );
}
else
{
query = wxT( "SELECT DISTINCT song_playcount FROM songs " ) \
wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_PLAYCOUNTS );
query += wxT( " ORDER BY song_playcount;" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
int PlayCount = dbRes.GetInt( 0 );
// To avoid using the 0 as 0 is used for All
PlayCounts->Add( new guListItem( PlayCount + 1, wxString::Format( wxT( "%i" ), PlayCount ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetAlbumArtists( guListItems * Items, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( FullList )
{
query = wxT( "SELECT song_albumartistid, song_albumartist FROM songs GROUP BY song_albumartistid;" );
}
else if( !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() || m_CoFilters.Count() ) )
{
query = wxT( "SELECT song_albumartistid, song_albumartist FROM songs WHERE song_albumartist > '' " \
"GROUP BY song_albumartistid ORDER BY song_albumartist" );
}
else
{
query = wxT( "SELECT song_albumartistid, song_albumartist FROM songs WHERE song_albumartist > '' AND " ) +
FiltersSQL( guLIBRARY_FILTER_ALBUMARTISTS );
query += wxT( " GROUP BY song_albumartistid ORDER BY song_albumartist" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Items->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetComposers( guListItems * Items, const bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( FullList )
{
query = wxT( "SELECT song_composerid, song_composer FROM songs GROUP BY song_composerid;" );
}
else if( !( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ) )
{
query = wxT( "SELECT song_composerid, song_composer FROM songs WHERE song_composer > '' " \
"GROUP BY song_composerid ORDER BY song_composer" );
}
else
{
query = wxT( "SELECT song_composerid, song_composer FROM songs WHERE song_composer > '' AND " ) +
FiltersSQL( guLIBRARY_FILTER_COMPOSERS );
query += wxT( " GROUP BY song_composerid ORDER BY song_composer" );
}
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Items->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPaths( guListItems * Paths, bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString CoverPath;
//guLogMessage( wxT( "guDbLibrary::GetPaths" ) );
query = wxT( "SELECT DISTINCT song_pathid, song_path FROM songs GROUP BY song_pathid" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Paths->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetAlbumsOrder( const int order )
{
m_AlbumsOrder = order;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetAlbums( guAlbumItems * Albums, bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
//guLogMessage( wxT( "guDbLibrary::GetAlbums" )
query = wxT( "SELECT song_albumid, song_album, song_artistid, song_artist, song_albumartist, song_coverid, MAX(song_year) FROM songs " );
if( FullList )
{
query += wxT( "GROUP BY song_albumid " );
}
else
{
if( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ||
m_AAFilters.Count() || m_ArFilters.Count() || m_CoFilters.Count() || m_YeFilters.Count() )
{
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_ALBUMS );
}
query += wxT( " GROUP BY song_albumid " );
query += wxT( " ORDER BY " );
switch( m_AlbumsOrder )
{
case guALBUMS_ORDER_NAME :
query += wxT( "song_album, song_disk" );
break;
case guALBUMS_ORDER_YEAR :
query += wxT( "song_year, song_album, song_disk" );
break;
case guALBUMS_ORDER_YEAR_REVERSE :
query += wxT( "song_year DESC, song_album, song_disk" );
break;
case guALBUMS_ORDER_ARTIST_NAME :
query += wxT( "coalesce(nullif(song_albumartist,''),song_artist) COLLATE NOCASE, song_album, song_disk " );
break;
case guALBUMS_ORDER_ARTIST_YEAR :
query += wxT( "coalesce(nullif(song_albumartist,''),song_artist) COLLATE NOCASE, song_year, song_album, song_disk" );
break;
case guALBUMS_ORDER_ARTIST_YEAR_REVERSE :
default :
query += wxT( "coalesce(nullif(song_albumartist,''),song_artist) COLLATE NOCASE, song_year DESC, song_album, song_disk" );
break;
}
}
//guLogMessage( wxT( "GetAlbums: %s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
//query = wxT( "SELECT song_albumid, song_album, song_artistid, song_artist, song_albumartist, song_coverid, MAX(song_year) FROM songs " );
guAlbumItem * AlbumItem = new guAlbumItem();
AlbumItem->m_Id = dbRes.GetInt( 0 );
AlbumItem->m_Name = dbRes.GetString( 1 );
AlbumItem->m_ArtistId = dbRes.GetInt( 2 );
AlbumItem->m_ArtistName = dbRes.GetString( 4 );
if( AlbumItem->m_ArtistName.IsEmpty() )
AlbumItem->m_ArtistName = dbRes.GetString( 3 );
AlbumItem->m_CoverId = dbRes.GetInt( 5 );
AlbumItem->m_Year = dbRes.GetInt( 6 );
AlbumItem->m_Thumb = GetCoverBitmap( AlbumItem->m_CoverId );
Albums->Add( AlbumItem );
}
dbRes.Finalize();
// return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetAlbums( guListItems * Albums, bool FullList )
{
wxString query;
wxSQLite3ResultSet dbRes;
//guLogMessage( wxT( "guDbLibrary::GetAlbums" )
query = wxT( "SELECT song_albumid, song_album FROM songs " );
if( FullList )
{
query += wxT( "GROUP BY song_albumid " );
}
else
{
if( m_TeFilters.Count() || m_LaFilters.Count() || m_GeFilters.Count() ||
m_AAFilters.Count() || m_ArFilters.Count() || m_CoFilters.Count() || m_YeFilters.Count() )
{
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_ALBUMS );
}
query += wxT( " GROUP BY song_albumid " );
}
//guLogMessage( wxT( "GetAlbums: %s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
guListItem * AlbumItem = new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) );
Albums->Add( AlbumItem );
}
dbRes.Finalize();
}
const wxString DynPlayListToSQLQuery( guDynPlayList * playlist );
// -------------------------------------------------------------------------------- //
bool guDbLibrary::GetAlbumDetails( const int albumid, int * year, int * trackcount )
{
wxString query;
wxSQLite3ResultSet dbRes;
bool RetVal = false;
query = wxString::Format( wxT( "SELECT MAX(song_year), COUNT(song_id) FROM songs WHERE song_albumid = %i;" ), albumid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
* year = dbRes.GetInt( 0 );
* trackcount = dbRes.GetInt( 1 );
RetVal = true;
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumYear( const int albumid )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
query = wxString::Format( wxT( "SELECT MAX(song_year) FROM songs WHERE song_albumid = %i;" ), albumid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
RetVal = dbRes.GetInt( 0 );
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumTrackCount( const int albumid )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
query = wxString::Format( wxT( "SELECT COUNT( song_id ) FROM songs WHERE song_albumid = %i" ), albumid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
RetVal = dbRes.GetInt( 0 );
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString inline AlbumBrowserTextFilterToSQL( const wxArrayString &textfilters )
{
wxString RetVal;
int count = textfilters.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
wxString Filter = escape_query_str( textfilters[ index ] );
RetVal += wxT( "( song_album LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_albumartist LIKE '%" ) + Filter + wxT( "%' OR " );
RetVal += wxT( " song_artist LIKE '%" ) + Filter + wxT( "%' ) " );
RetVal += wxT( "AND " );
}
RetVal = RetVal.RemoveLast( 4 );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumsCount( guDynPlayList * filter, const wxArrayString &textfilters )
{
wxString query;
wxString postquery;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
query = wxT( "SELECT COUNT( DISTINCT song_albumid ) FROM songs " );
if( filter )
{
postquery += DynPlayListToSQLQuery( filter );
}
if( textfilters.Count() )
{
if( postquery.IsEmpty() )
postquery = wxT( "WHERE " );
else
postquery += wxT( " AND " );
//postquery += wxT( "song_albumid = album_id AND song_artistid = artist_id AND " );
postquery += AlbumBrowserTextFilterToSQL( textfilters );
}
dbRes = ExecuteQuery( query + postquery );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
guLogMessage( wxT( "Got %i albums" ), RetVal );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbums( guAlbumBrowserItemArray * items, guDynPlayList * filter,
const wxArrayString &textfilters, const int start, const int count, const int order )
{
if( !count )
return 0;
wxString query;
wxSQLite3ResultSet dbRes;
wxString subquery;
query = wxT( "SELECT song_albumid, song_album, song_artistid, song_albumartist, song_artist, song_coverid FROM songs " );
if( filter )
{
subquery = DynPlayListToSQLQuery( filter );
}
if( textfilters.Count() )
{
subquery += subquery.IsEmpty() ? wxT( "WHERE " ) : wxT( " AND " );
subquery += AlbumBrowserTextFilterToSQL( textfilters );
}
query += subquery + wxT( " GROUP BY song_albumid ORDER BY " );
switch( order )
{
case guALBUMS_ORDER_NAME :
query += wxT( "song_album" );
break;
case guALBUMS_ORDER_YEAR :
query += wxT( "song_year" );
break;
case guALBUMS_ORDER_YEAR_REVERSE :
query += wxT( "song_year DESC" );
break;
case guALBUMS_ORDER_ARTIST_NAME :
query += wxT( "coalesce(nullif(song_albumartist, ''),song_artist) COLLATE NOCASE, song_album " );
break;
case guALBUMS_ORDER_ARTIST_YEAR :
query += wxT( "coalesce(nullif(song_albumartist,''),song_artist) COLLATE NOCASE, song_year" );
break;
case guALBUMS_ORDER_ADDEDTIME :
query += wxT( "song_addedtime DESC,song_album,song_disk " );
break;
case guALBUMS_ORDER_ARTIST_YEAR_REVERSE :
default :
query += wxT( "coalesce(nullif(song_albumartist,''),song_artist) COLLATE NOCASE, song_year DESC" );
break;
}
query += wxString::Format( wxT( " LIMIT %i, %i" ), start, count );
//guLogMessage( wxT( "GetAlbums:\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
guAlbumBrowserItem * Item = new guAlbumBrowserItem();
Item->m_AlbumId = dbRes.GetInt( 0 ); //AlbumId;
Item->m_AlbumName = dbRes.GetString( 1 );
Item->m_ArtistId = dbRes.GetInt( 2 );
Item->m_ArtistName = dbRes.GetString( 3 );
if( Item->m_ArtistName.IsEmpty() )
Item->m_ArtistName = dbRes.GetString( 4 );
Item->m_CoverId = dbRes.GetInt( 5 );
Item->m_CoverBitmap = GetCoverBitmap( Item->m_CoverId, false );
Item->m_Year = 0; //dbRes.GetInt( 4 );
Item->m_TrackCount = 0; //dbRes.GetInt( 5 );
items->Add( Item );
}
dbRes.Finalize();
return items->Count();
}
// -------------------------------------------------------------------------------- //
wxArrayString guDbLibrary::GetAlbumsPaths( const wxArrayInt &AlbumIds )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxArrayString RetVal;
query = wxT( "SELECT DISTINCT song_path FROM songs WHERE song_albumid IN " ) + ArrayIntToStrList( AlbumIds );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
RetVal.Add( dbRes.GetString( 0 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetStaticPlayList( const wxString &path )
{
wxString query;
wxSQLite3ResultSet dbRes;
int PLId = wxNOT_FOUND;
query = wxString::Format( wxT( "SELECT playlist_id FROM playlists WHERE playlist_path = '%s' AND playlist_type = 0 LIMIT 1" ),
escape_query_str( path ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
PLId = dbRes.GetInt( 0 );
}
dbRes.Finalize();
return PLId;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::CreateStaticPlayList( const wxString &path, const wxArrayInt &songs )
{
int PlayListId = 0;
wxString query;
// wxSQLite3ResultSet dbRes;
wxString Name;
wxString Path = path;
if( guPlaylistFile::IsValidPlayList( path ) )
{
Name = wxFileNameFromPath( path ).BeforeLast( wxT( '.' ) );
}
else
{
Name = path;
Path = wxEmptyString;
}
query = wxString::Format( wxT( "INSERT INTO playlists( playlist_id, playlist_name, playlist_type, playlist_path ) VALUES( NULL, '%s', 0, '%s' );" ),
escape_query_str( Name ).c_str(),
escape_query_str( Path ).c_str() );
if( ExecuteUpdate( query ) )
{
PlayListId = GetLastRowId();
}
//dbRes.Finalize();
if( PlayListId )
{
int count = songs.Count();
for( int index = 0; index < count; index++ )
{
// query.Add( wxT( "CREATE TABLE IF NOT EXISTS playlists( playlist_id INTEGER PRIMARY KEY AUTOINCREMENT, playlist_name varchar(100), "
// "playlist_type INTEGER(2));" ) );
// query.Add( wxT( "CREATE TABLE IF NOT EXISTS plsets( plset_id INTEGER PRIMARY KEY AUTOINCREMENT, plset_plid INTEGER, plset_songid INTEGER, "
// "plset_type INTEGER(2), plset_option INTEGER(2), plset_text TEXT(255), plset_option2 INTEGER );" ) );
query = wxString::Format( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, plset_type, plset_option, plset_text, plset_option2 ) " \
"VALUES( NULL, %u, %u, 0, 0, '', 0 );" ),
PlayListId,
songs[ index ] );
ExecuteUpdate( query );
//dbRes.Finalize();
}
}
return PlayListId;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::UpdateStaticPlayList( const int plid, const wxArrayInt &tracks )
{
wxString query;
query = wxString::Format( wxT( "DELETE FROM plsets WHERE plset_plid = %u;" ), plid );
ExecuteUpdate( query );
return AppendStaticPlayList( plid, tracks );
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::AppendStaticPlayList( const int plid, const wxArrayInt &tracks )
{
wxString query;
int count = tracks.Count();
for( int index = 0; index < count; index++ )
{
query = wxString::Format( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, plset_type, plset_option, plset_text, plset_option2 ) "
"VALUES( NULL, %u, %u, 0, 0, '', 0 );" ),
plid,
tracks[ index ] );
ExecuteUpdate( query );
}
return tracks.Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::DelPlaylistSetIds( const int plid, const wxArrayInt &setids )
{
wxString query;
query = wxString::Format( wxT( "DELETE FROM plsets WHERE plset_plid = %u AND " ), plid );
query += ArrayToFilter( setids, wxT( "plset_id" ) );
//guLogMessage( wxT( "DelPlayListSetIds:\n%s" ), query.c_str() );
int RetVal = ExecuteUpdate( query );
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListFiles( const int plid, wxFileDataObject * files )
{
int Count = 0;
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT song_filename, song_path FROM plsets, songs " \
"WHERE plset_songid = song_id AND plset_plid = " );
query += wxString::Format( wxT( "%u" ), plid );
//guLogMessage( wxT( "GetPlayListFiles:\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
files->AddFile( dbRes.GetString( 1 ) + dbRes.GetString( 0 ) );
Count++;
}
dbRes.Finalize();
return Count;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateStaticPlayListFile( const int plid )
{
wxString PlaylistPath = GetPlayListPath( plid );
if( !PlaylistPath.IsEmpty() )
{
wxFileName FileName( PlaylistPath );
if( FileName.Normalize() )
{
guTrackArray Tracks;
GetPlayListSongs( plid, guPLAYLIST_TYPE_STATIC, &Tracks, NULL, NULL );
guPlaylistFile PlayListFile;
PlayListFile.SetName( FileName.GetFullPath() );
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
PlayListFile.AddItem( Tracks[ Index ].m_FileName,
Tracks[ Index ].m_ArtistName + wxT( " - " ) + Tracks[ Index ].m_SongName, Tracks[ Index ].m_Length / 1000 );
}
PlayListFile.Save( FileName.GetFullPath() );
}
}
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::CreateDynamicPlayList( const wxString &name, const guDynPlayList * playlist )
{
int PlayListId = 0;
wxString query;
wxSQLite3ResultSet dbRes;
// playlists( playlist_id INTEGER PRIMARY KEY AUTOINCREMENT, playlist_name varchar(100), "
// "playlist_type INTEGER(2), playlist_limited BOOLEAN, playlist_limitvalue INTEGER, playlist_limittype INTEGER(2), "
// "playlist_sorted BOOLEAN, playlist_sorttype INTEGER(2), playlist_sortdesc BOOLEAN, playlist_anyoption BOOLEAN);" ) );
query = wxT( "INSERT INTO playlists( playlist_id, playlist_name, playlist_type, " \
"playlist_limited, playlist_limitvalue, playlist_limittype, " \
"playlist_sorted, playlist_sorttype, playlist_sortdesc, " \
"playlist_anyoption ) " );
query += wxString::Format( wxT( "VALUES( NULL, '%s', %u, %u, %u, %u, %u, %u, %u, %u );" ),
escape_query_str( name ).c_str(),
guPLAYLIST_TYPE_DYNAMIC,
playlist->m_Limited, playlist->m_LimitValue, playlist->m_LimitType,
playlist->m_Sorted, playlist->m_SortType, playlist->m_SortDesc,
playlist->m_AnyOption );
if( ExecuteUpdate( query ) == 1 )
{
PlayListId = GetLastRowId();
}
if( PlayListId )
{
int count = playlist->m_Filters.Count();
for( int index = 0; index < count; index++ )
{
guFilterItem * FilterItem = &playlist->m_Filters[ index ];
query = wxString::Format( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, plset_type, plset_option, plset_text, plset_number, plset_option2 ) "
"VALUES( NULL, %u, 0, %u, %u, '%s', %u, %u );" ),
PlayListId,
FilterItem->m_Type,
FilterItem->m_Option,
escape_query_str( FilterItem->m_Text ).c_str(),
FilterItem->m_Number,
FilterItem->m_Option2
);
ExecuteUpdate( query );
}
}
return PlayListId;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListsCount( void )
{
int RetVal = 0;
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT COUNT( playlist_id ) FROM playlists" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPlayLists( guListItems &playlists )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT playlist_id, playlist_name FROM playlists ORDER BY playlist_name" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
playlists.Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPlayLists( wxArrayString &playlistnames )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT playlist_name FROM playlists" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
playlistnames.Add( dbRes.GetString( 0 ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPlayLists( wxArrayInt &playlistids )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT playlist_id FROM playlists" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
playlistids.Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetPlayLists( guListItems * PlayLists, const int type, const wxArrayString * textfilters )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT playlist_id, playlist_name FROM playlists " \
"WHERE playlist_type = %u " ), type );
if( textfilters && textfilters->Count() )
{
int Count = textfilters->Count();
for( int Index = 0; Index < Count; Index++ )
{
wxString Filter = escape_query_str( ( * textfilters )[ Index ] );
query += wxT( "AND playlist_name LIKE '%" ) + Filter + wxT( "%' " );
}
}
query += wxT( "ORDER BY playlist_name COLLATE NOCASE;" ),
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
PlayLists->Add( new guListItem( dbRes.GetInt( 0 ), dbRes.GetString( 1 ) ) );
}
dbRes.Finalize();
// return RetVal;
}
// -------------------------------------------------------------------------------- //
const wxString DynPLStringOption( int option, const wxString &text )
{
wxString TextParam = text;
escape_query_str( &TextParam );
wxString FmtStr;
switch( option )
{
case guDYNAMIC_FILTER_OPTION_STRING_CONTAINS : // contains
FmtStr = wxT( "LIKE '%%%s%%'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_NOT_CONTAINS : // not contains
FmtStr = wxT( "NOT LIKE '%%%s%%'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_IS : // IS
FmtStr = wxT( "= '%s'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_ISNOT : // IS NOT
FmtStr = wxT( "!= '%s'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_START_WITH : // START WITH
FmtStr = wxT( "LIKE '%s%%'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_ENDS_WITH : // ENDS WITH
FmtStr = wxT( "LIKE '%%%s'" );
break;
}
return wxString::Format( FmtStr, TextParam.c_str() );
}
// -------------------------------------------------------------------------------- //
const wxString DynPLLabelOption( int option, const wxString &text )
{
wxString TextParam = text;
escape_query_str( &TextParam );
wxString FmtStr;
switch( option )
{
case guDYNAMIC_FILTER_OPTION_STRING_NOT_CONTAINS : // not contains
case guDYNAMIC_FILTER_OPTION_STRING_CONTAINS : // contains
FmtStr = wxT( "LIKE '%%%s%%'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_IS : // IS
case guDYNAMIC_FILTER_OPTION_STRING_ISNOT : // IS NOT
FmtStr = wxT( "= '%s'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_START_WITH : // START WITH
FmtStr = wxT( "LIKE '%s%%'" );
break;
case guDYNAMIC_FILTER_OPTION_STRING_ENDS_WITH : // ENDS WITH
FmtStr = wxT( "LIKE '%%%s'" );
break;
}
return wxString::Format( FmtStr, TextParam.c_str() );
}
// -------------------------------------------------------------------------------- //
const wxString DynPLYearOption( const int option, const int year )
{
wxString FmtStr;
switch( option )
{
case guDYNAMIC_FILTER_OPTION_YEAR_IS :
FmtStr = wxT( "= %u" );
break;
case guDYNAMIC_FILTER_OPTION_YEAR_ISNOT :
FmtStr = wxT( "!= %u" );
break;
case guDYNAMIC_FILTER_OPTION_YEAR_AFTER :
FmtStr = wxT( "> %u" );
break;
case guDYNAMIC_FILTER_OPTION_YEAR_BEFORE :
FmtStr = wxT( "< %u" );
break;
}
return wxString::Format( FmtStr, year );
}
// -------------------------------------------------------------------------------- //
const wxString DynPLNumericOption( const int option, const int value )
{
wxString FmtStr;
switch( option )
{
case guDYNAMIC_FILTER_OPTION_NUMERIC_IS :
FmtStr = wxT( "= %u" );
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_ISNOT :
FmtStr = wxT( "!= %u" );
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_AT_LEAST :
FmtStr = wxT( ">= %u" );
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_AT_MOST :
FmtStr = wxT( "<= %u" );
break;
}
return wxString::Format( FmtStr, value );
}
// -------------------------------------------------------------------------------- //
unsigned long DynPLDateOption2[] = {
60, // Minutes
3600, // Hours
86400, // Days
604800, // Weeks
2592000 // Months
};
// -------------------------------------------------------------------------------- //
const wxString DynPLDateOption( const int option, const int value, const int option2 )
{
unsigned long Time;
wxString FmtStr;
switch( option )
{
case guDYNAMIC_FILTER_OPTION_DATE_IN_THE_LAST : // IN_THE_LAST
{
FmtStr = wxT( ">= %lu" );
break;
}
case guDYNAMIC_FILTER_OPTION_DATE_BEFORE_THE_LAST : // BEFORE_THE_LAST
{
FmtStr = wxT( "< %lu" );
break;
}
}
Time = wxDateTime::GetTimeNow() - ( value * DynPLDateOption2[ option2 ] );
return wxString::Format( FmtStr, Time );
}
// -------------------------------------------------------------------------------- //
const wxString DynPlayListToSQLQuery( guDynPlayList * playlist )
{
if( !playlist->m_Filters.Count() )
return wxEmptyString;
wxString query = wxEmptyString;
wxString dbNames = wxEmptyString;
wxString dbSets = wxEmptyString;
int count = playlist->m_Filters.Count();
for( int index = 0; index < count; index++ )
{
if( index )
{
query += playlist->m_AnyOption ? wxT( " OR " ) : wxT( " AND " );
}
switch( playlist->m_Filters[ index ].m_Type )
{
case guDYNAMIC_FILTER_TYPE_TITLE : // TITLE
query += wxT( "song_name " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_ARTIST : // ARTIST
query += wxT( "song_artist " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_ALBUMARTIST : // ALBUMARTIST
query += wxT( "song_albumartist " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_ALBUM : // ALBUM
query += wxT( "song_album " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_GENRE : // GENRE
query += wxT( "song_genre " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_LABEL : // LABEL
if( playlist->m_Filters[ index ].m_Option == guDYNAMIC_FILTER_OPTION_LABELS_NOTSET )
{
query += wxT( "( song_id NOT IN ( SELECT DISTINCT settag_songid FROM settags WHERE settag_songid > 0 ) ) " );
}
else
{
wxString TagNameFilter = wxT( "SELECT tag_id FROM tags WHERE tag_name " ) +
DynPLLabelOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
wxString Option;
wxString Condition;
switch( playlist->m_Filters[ index ].m_Option )
{
case guDYNAMIC_FILTER_OPTION_STRING_CONTAINS : // contains
case guDYNAMIC_FILTER_OPTION_STRING_IS : // IS
case guDYNAMIC_FILTER_OPTION_STRING_START_WITH : // START WITH
case guDYNAMIC_FILTER_OPTION_STRING_ENDS_WITH : // ENDS WITH
Option = wxT( "IN " );
Condition = wxT( "OR " );
break;
case guDYNAMIC_FILTER_OPTION_STRING_NOT_CONTAINS : // not contains
case guDYNAMIC_FILTER_OPTION_STRING_ISNOT : // IS NOT
Option = wxT( "NOT IN " );
Condition = wxT( "AND " );
break;
}
query += wxT( "((song_artistid " ) + Option + wxT( "(SELECT settag_artistid FROM settags WHERE settag_tagid IN (" );
query += TagNameFilter + wxT( ") and settag_artistid > 0 )) " ) + Condition;
query += wxT( "(song_albumid " ) + Option + wxT( "(SELECT settag_albumid FROM settags WHERE settag_tagid IN (" );
query += TagNameFilter + wxT( ") and settag_albumid > 0 )) " ) + Condition;
query += wxT( "(song_id ") + Option + wxT( "(SELECT settag_songid FROM settags WHERE settag_tagid IN (" );
query += TagNameFilter + wxT( ") and settag_songid > 0 )))" );
}
break;
case guDYNAMIC_FILTER_TYPE_COMPOSER : // COMPOSER
query += wxT( "song_composer " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_COMMENT : // COMMENT
query += wxT( "song_comment " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_PATH : // PATH
query += wxT( "song_path " ) + DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text );
break;
case guDYNAMIC_FILTER_TYPE_YEAR : // YEAR
{
query += wxT( "( song_year " ) +
DynPLYearOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_RATING : // RATING
{
query += wxT( "( song_rating " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_LENGTH : // LENGTH
{
query += wxT( "( song_length " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number * 1000 ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_PLAYCOUNT : // PLAYCOUNT
{
query += wxT( "( song_playcount " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_LASTPLAY :
{
query += wxT( "( IFNULL( song_lastplay, 0 ) " ) +
DynPLDateOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number,
playlist->m_Filters[ index ].m_Option2 ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_ADDEDDATE :
{
query += wxT( "( song_addedtime " ) +
DynPLDateOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number,
playlist->m_Filters[ index ].m_Option2 ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_TRACKNUMBER : // TRACK NUMBER
{
query += wxT( "( song_number " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_BITRATE : // BITRATE
{
query += wxT( "( song_bitrate " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_SIZE : // SIZE
{
query += wxT( "( song_filesize " ) +
DynPLNumericOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Number ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_DISK : // DISK
{
query += wxT( "( song_disk " ) +
DynPLStringOption( playlist->m_Filters[ index ].m_Option,
playlist->m_Filters[ index ].m_Text ) + wxT( ")" );
break;
}
case guDYNAMIC_FILTER_TYPE_HASARTWORK : // HAS ARTWORK
{
query += wxT( "( song_coverid " );
query += ( playlist->m_Filters[ index ].m_Option ? wxT( "> 0 )" ) : wxT( "< 1 )" ) );
break;
}
}
}
// SORTING Options
//guLogMessage( wxT( "Sort: %u %u %u" ), playlist->m_Sorted, playlist->m_SortType, playlist->m_SortDesc );
wxString sort;
if( playlist->m_Sorted )
{
sort = wxT( " ORDER BY " );
switch( playlist->m_SortType )
{
case guDYNAMIC_FILTER_ORDER_TITLE : sort += wxT( "song_name" ); break;
case guDYNAMIC_FILTER_ORDER_ARTIST : sort += wxT( "song_artist" ); break;
case guDYNAMIC_FILTER_ORDER_ALBUMARTIST : sort += wxT( "song_albumartist" ); break;
case guDYNAMIC_FILTER_ORDER_ALBUM : sort += wxT( "song_album" ); break;
case guDYNAMIC_FILTER_ORDER_GENRE : sort += wxT( "song_genre" ); break;
case guDYNAMIC_FILTER_ORDER_COMPOSER : sort += wxT( "song_composer" ); break;
case guDYNAMIC_FILTER_ORDER_YEAR : sort += wxT( "song_year" ); break;
case guDYNAMIC_FILTER_ORDER_RATING : sort += wxT( "song_rating" ); break;
case guDYNAMIC_FILTER_ORDER_LENGTH : sort += wxT( "song_length" ); break;
case guDYNAMIC_FILTER_ORDER_PLAYCOUNT : sort += wxT( "song_playcount" ); break;
case guDYNAMIC_FILTER_ORDER_LASTPLAY : sort += wxT( "song_lastplay" ); break;
case guDYNAMIC_FILTER_ORDER_ADDEDDATE : sort += wxT( "song_addedtime" ); break;
case guDYNAMIC_FILTER_ORDER_RANDOM : sort += wxT( "RANDOM()" ); break;
}
if( playlist->m_SortDesc )
sort += wxT( " DESC" );
switch( playlist->m_SortType )
{
case guDYNAMIC_FILTER_ORDER_ARTIST : sort += wxT( ", song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_ALBUMARTIST : sort += wxT( ", song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_ALBUM : sort += wxT( ", song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_GENRE : sort += wxT( ", song_artist, song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_COMPOSER : sort += wxT( ", song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_YEAR : sort += wxT( ", song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_RATING : sort += wxT( ", song_album, song_disk, song_number" ); break;
case guDYNAMIC_FILTER_ORDER_ADDEDDATE : sort += wxT( ", song_album, song_disk, song_number" ); break;
}
}
//guLogMessage( wxT( "..., %s%s%s" ), dbNames.c_str(), query.c_str(), sort.c_str() );
if( !dbSets.IsEmpty() )
{
dbSets = wxT( "( " ) + dbSets + wxT( ") AND " );
}
return dbNames + wxT( " WHERE " ) + dbSets + wxT( "(" ) + query + wxT( ")" ) + sort;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSongIds( const int plid, wxArrayInt * tracks )
{
wxString query;
wxSQLite3ResultSet dbRes;
query += wxString::Format( wxT( "SELECT plset_songid FROM plsets WHERE plset_plid = %u" ), plid );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
tracks->Add( dbRes.GetInt( 0 ) );;
}
dbRes.Finalize();
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::GetPlayListQuery( const int plid )
{
wxString RetVal = wxEmptyString;
if( plid )
{
int PlType = GetPlayListType( plid );
if( PlType == guPLAYLIST_TYPE_STATIC )
{
RetVal = wxString::Format( wxT( "SELECT plset_songid FROM plsets WHERE plset_plid = %u" ), plid );
}
else if( PlType == guPLAYLIST_TYPE_DYNAMIC )
{
guDynPlayList PlayList;
GetDynamicPlayList( plid, &PlayList );
RetVal = wxT( "SELECT song_id FROM songs " ) + DynPlayListToSQLQuery( &PlayList );
}
}
//guLogMessage( wxT( "::GetPlaylistQuery %s"), RetVal.c_str() );
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSongs( const int plid, guTrackArray * tracks )
{
int PlType = GetPlayListType( plid );
if( PlType != wxNOT_FOUND )
{
return GetPlayListSongs( plid, PlType, tracks, NULL, NULL );
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSongs( const int plid, const int pltype, guTrackArray * tracks,
wxArrayInt * setids, wxLongLong * len, wxLongLong * size,
const int order, const bool orderdesc )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Track;
wxLongLong TrackLength = 0;
wxLongLong TrackSize = 0;
if( plid )
{
if( pltype == guPLAYLIST_TYPE_STATIC )
{
query = wxT( "SELECT song_id, song_name, song_genreid, song_genre, song_artistid, song_artist, " \
"song_albumartistid, song_albumartist, song_composerid, song_composer, song_albumid, song_album, " \
"song_pathid, song_path, song_filename, song_format, song_disk, song_number, song_year, song_comment, " \
"song_coverid, song_offset, song_length, song_bitrate, song_rating, song_playcount, " \
"song_addedtime, song_lastplay, song_filesize, plset_id " \
"FROM songs " );
query += wxString::Format( wxT( ", plsets WHERE plset_songid = song_id AND plset_plid = %u" ), plid );
query += GetSongsSortSQL( order, orderdesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Track = new guTrack();
FillTrackFromDb( Track, &dbRes );
tracks->Add( Track );
TrackLength += Track->m_Length;
TrackSize += Track->m_FileSize;
if( setids )
setids->Add( dbRes.GetInt( 29 ) );
}
dbRes.Finalize();
}
else //guPLAYLIST_TYPE_DYNAMIC
{
guDynPlayList PlayList;
GetDynamicPlayList( plid, &PlayList );
wxLongLong Limit;
wxLongLong Count = 0;
if( PlayList.m_Limited )
{
switch( PlayList.m_LimitType )
{
case guDYNAMIC_FILTER_LIMIT_TRACKS : // TRACKS
Limit = PlayList.m_LimitValue;
break;
case guDYNAMIC_FILTER_LIMIT_MINUTES : // Minutes -> to seconds
Limit = PlayList.m_LimitValue * 60000;
break;
case guDYNAMIC_FILTER_LIMIT_MEGABYTES : // MB -> To bytes
Limit = PlayList.m_LimitValue;
Limit *= 1000000;
break;
case guDYNAMIC_FILTER_LIMIT_GIGABYTES : // GB -> to bytes
Limit = PlayList.m_LimitValue;
Limit *= 1000000000;
break;
}
}
query = wxT( "SELECT song_id, song_name, song_genreid, song_genre, song_artistid, song_artist, " \
"song_albumartistid, song_albumartist, song_composerid, song_composer, song_albumid, song_album, " \
"song_pathid, song_path, song_filename, song_format, song_disk, song_number, song_year, song_comment, " \
"song_coverid, song_offset, song_length, song_bitrate, song_rating, song_playcount, " \
"song_addedtime, song_lastplay, song_filesize " \
"FROM songs " );
query += DynPlayListToSQLQuery( &PlayList );
if( !PlayList.m_Sorted && ( order != wxNOT_FOUND ) )
{
query += GetSongsSortSQL( order, orderdesc );
}
//guLogMessage( wxT( "GetPlayListSongs: <<%s>>" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
guTrack * Track = new guTrack();
FillTrackFromDb( Track, &dbRes );
if( PlayList.m_Limited )
{
//guLogMessage( wxT( "Limit: %lli / %lli" ), Count.GetValue(), Limit.GetValue() );
if( PlayList.m_LimitType == guDYNAMIC_FILTER_LIMIT_TRACKS )
{
Count++;
}
else if( PlayList.m_LimitType == guDYNAMIC_FILTER_LIMIT_MINUTES )
{
Count += Track->m_Length;
}
else
{
Count += Track->m_FileSize;
}
if( Count > Limit )
break;
}
tracks->Add( Track );
TrackLength += Track->m_Length;
TrackSize += Track->m_FileSize;
}
dbRes.Finalize();
}
}
if( len )
* len = TrackLength;
if( size )
* size = TrackSize;
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSongs( const wxArrayInt &ids, const wxArrayInt &types, guTrackArray * tracks,
wxArrayInt * setids, wxLongLong * len, wxLongLong * size, const int order, const bool orderdesc )
{
int Count = wxMin( ids.Count(), types.Count() );
if( Count == 1 )
{
return GetPlayListSongs( ids[ 0 ], types[ 0 ], tracks, setids, len, size, order, orderdesc );
}
//
// Only get multiple ids for static playlists
//
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Track;
wxLongLong TrackLength = 0;
wxLongLong TrackSize = 0;
query = wxT( "SELECT song_id, song_name, song_genreid, song_genre, song_artistid, song_artist, " \
"song_albumartistid, song_albumartist, song_composerid, song_composer, song_albumid, song_album, " \
"song_pathid, song_path, song_filename, song_format, song_disk, song_number, song_year, song_comment, " \
"song_coverid, song_offset, song_length, song_bitrate, song_rating, song_playcount, " \
"song_addedtime, song_lastplay, song_filesize, plset_id " \
"FROM songs " );
query += wxT( ", plsets WHERE plset_songid = song_id AND plset_plid IN (" );
for( int Index = 0; Index < Count; Index++ )
{
query += wxString::Format( wxT( "%u," ), ids[ Index ] );
}
query.RemoveLast( 1 );
query += wxT( ")" ) + GetSongsSortSQL( order, orderdesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Track = new guTrack();
FillTrackFromDb( Track, &dbRes );
tracks->Add( Track );
TrackLength += Track->m_Length;
TrackSize += Track->m_FileSize;
if( setids )
setids->Add( dbRes.GetInt( 29 ) );
}
dbRes.Finalize();
if( len )
* len = TrackLength;
if( size )
* size = TrackSize;
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSetIds( const int plid, wxArrayInt * setids )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT plset_id FROM plsets WHERE plset_plid = " );
query += wxString::Format( wxT( "%u" ), plid );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
setids->Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
return setids->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListSetIds( const wxArrayInt &plids, wxArrayInt * setids )
{
int Count = plids.Count();
for( int Index = 0; Index < Count; Index++ )
{
GetPlayListSetIds( plids[ Index ], setids );
}
return setids->Count();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetDynamicPlayList( const int plid, guDynPlayList * playlist )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT playlist_name, playlist_limited, playlist_limitvalue, playlist_limittype, " \
"playlist_sorted, playlist_sorttype, playlist_sortdesc, playlist_anyoption " \
"FROM playlists WHERE playlist_id = %u LIMIT 1;" ), plid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
playlist->m_Id = plid;
playlist->m_Name = dbRes.GetString( 0 );
playlist->m_Limited = dbRes.GetBool( 1 );
playlist->m_LimitValue = dbRes.GetInt( 2 );
playlist->m_LimitType = dbRes.GetInt( 3 );
playlist->m_Sorted = dbRes.GetBool( 4 );
playlist->m_SortType = dbRes.GetInt( 5 );
playlist->m_SortDesc = dbRes.GetBool( 6 );
playlist->m_AnyOption = dbRes.GetBool( 7 );
}
dbRes.Finalize();
if( playlist->m_Id )
{
query = wxString::Format( wxT( "SELECT plset_type, plset_option, plset_text, plset_number, plset_option2 " \
"FROM plsets WHERE plset_plid = %u;" ), plid );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
guFilterItem * FilterItem = new guFilterItem();
FilterItem->m_Type = dbRes.GetInt( 0 );
FilterItem->m_Option = dbRes.GetInt( 1 );
FilterItem->m_Text = dbRes.GetString( 2 );
FilterItem->m_Number = dbRes.GetInt( 3 );
FilterItem->m_Option2 = dbRes.GetInt( 4 );
FilterItem->SetFilterLabel();
playlist->m_Filters.Add( FilterItem );
}
dbRes.Finalize();
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateDynamicPlayList( const int plid, const guDynPlayList * playlist )
{
wxString query;
query = wxString::Format( wxT( "UPDATE playlists SET playlist_name = '%s', " \
"playlist_limited = %u, playlist_limitvalue = %u, playlist_limittype = %u, " \
"playlist_sorted = %u, playlist_sorttype = %u, playlist_sortdesc = %u, " \
"playlist_anyoption = %u WHERE playlist_id = %u;" ),
escape_query_str( playlist->m_Name ).c_str(),
playlist->m_Limited, playlist->m_LimitValue, playlist->m_LimitType,
playlist->m_Sorted, playlist->m_SortType, playlist->m_SortDesc,
playlist->m_AnyOption,
plid );
ExecuteUpdate( query );
query = wxString::Format( wxT( "DELETE FROM plsets WHERE plset_plid = %u;" ), plid );
ExecuteUpdate( query );
int count = playlist->m_Filters.Count();
for( int index = 0; index < count; index++ )
{
guFilterItem * FilterItem = &playlist->m_Filters[ index ];
query = wxString::Format( wxT( "INSERT INTO plsets( plset_id, plset_plid, plset_songid, " \
"plset_type, plset_option, plset_text, plset_number, plset_option2 ) " \
"VALUES( NULL, %u, 0, %u, %u, '%s', %u, %u );" ),
plid,
FilterItem->m_Type,
FilterItem->m_Option,
escape_query_str( FilterItem->m_Text ).c_str(),
FilterItem->m_Number,
FilterItem->m_Option2
);
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::DeletePlayList( const int plid )
{
wxString query;
if( plid )
{
query = wxString::Format( wxT( "DELETE FROM plsets WHERE plset_plid = %u;" ), plid );
ExecuteUpdate( query );
query = wxString::Format( wxT( "DELETE FROM playlists WHERE playlist_id = %u;" ), plid );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::GetPlayListName( const int plid )
{
wxString RetVal;
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT playlist_name FROM playlists WHERE playlist_id = %u LIMIT 1;" ), plid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetString( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::GetPlayListPath( const int plid )
{
wxString RetVal;
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT playlist_path FROM playlists WHERE playlist_id = %u LIMIT 1;" ), plid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetString( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetPlayListPath( const int plid, const wxString &path )
{
wxString query;
if( plid )
{
query = wxString::Format( wxT( "UPDATE playlists SET playlist_path = '%s' WHERE playlist_id = %u;" ),
escape_query_str( path ).c_str(), plid );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetPlayListName( const int plid, const wxString &plname )
{
wxString query;
if( plid )
{
query = wxString::Format( wxT( "UPDATE playlists SET playlist_name = '%s' WHERE playlist_id = %u;" ),
escape_query_str( plname ).c_str(), plid );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetLabelsSongs( const wxArrayInt &Labels, guTrackArray * Songs )
{
wxString subquery;
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Labels.Count() )
{
subquery = ArrayIntToStrList( Labels );
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "( (song_artistid IN ( SELECT settag_artistid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_artistid > 0 ) ) OR" );
query += wxT( " (song_albumid IN ( SELECT settag_albumid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_albumid > 0 ) ) OR" );
query += wxT( " (song_id IN ( SELECT settag_songid FROM settags WHERE " \
"settag_tagid IN " ) + subquery + wxT( " and settag_songid > 0 ) ) ) " );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetGenresSongs( const wxArrayInt &Genres, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Genres.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_genreid IN " ) + ArrayIntToStrList( Genres );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetArtistsSongs( const wxArrayInt &Artists, guTrackArray * Songs, guTrackMode trackmode )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Artists.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_artistid IN " ) + ArrayIntToStrList( Artists );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Song->m_TrackMode = trackmode;
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetArtistsSongs( const wxArrayInt &Artists, guTrackArray * Songs,
const int trackcount, const int filterallow, const int filterdeny )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Artists.Count() )
{
wxString AllowPlQuery = GetPlayListQuery( filterallow );
wxString DenyPlQuery = GetPlayListQuery( filterdeny );
wxString Filters = wxEmptyString;
if( !AllowPlQuery.IsEmpty() )
{
Filters += wxT( "WHERE song_id IN ( " ) + AllowPlQuery + wxT( " ) " );
}
if( !DenyPlQuery.IsEmpty() )
{
Filters += Filters.IsEmpty() ? wxT( "WHERE " ) : wxT( "AND " );
Filters += wxT( "song_id NOT IN ( " ) + DenyPlQuery + wxT( " ) " );
}
query = GU_TRACKS_QUERYSTR;
query += Filters;
if( !Filters.IsEmpty() )
query += wxT( " AND" );
else
query += wxT( " WHERE" );
query += wxT( " song_artistid IN " ) + ArrayIntToStrList( Artists );
query += wxString::Format( wxT( " ORDER BY RANDOM() LIMIT %u" ), trackcount );
//guLogMessage( wxT( "GetArtistsSongs:\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Song->m_TrackMode = guTRACK_MODE_SMART;
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetArtistsAlbums( const wxArrayInt &Artists, wxArrayInt * Albums )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( Artists.Count() )
{
query = wxT( "SELECT DISTINCT song_albumid FROM songs WHERE song_artistid IN " );
query += ArrayIntToStrList( Artists );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Albums->Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
}
return Albums->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumArtistsAlbums( const wxArrayInt &albumartists, wxArrayInt * Albums )
{
wxString query;
wxSQLite3ResultSet dbRes;
if( albumartists.Count() )
{
query = wxT( "SELECT DISTINCT song_albumid FROM songs WHERE song_albumartistid IN " );
query += ArrayIntToStrList( albumartists );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Albums->Add( dbRes.GetInt( 0 ) );
}
dbRes.Finalize();
}
return Albums->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumsSongs( const wxArrayInt &Albums, guTrackArray * Songs, bool ordertoedit )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Albums.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_albumid IN " ) + ArrayIntToStrList( Albums );
if( ordertoedit )
{
query += wxT( " ORDER BY song_disk, song_number, song_filename" );
}
else
{
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
}
//guLogMessage( wxT( "GetAlbumsSongs: %s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetYearsSongs( const wxArrayInt &Years, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Years.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_year IN " ) + ArrayIntToStrList( Years );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetRatingsSongs( const wxArrayInt &Ratings, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Ratings.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_rating IN " ) + ArrayIntToStrList( Ratings );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayCountsSongs( const wxArrayInt &PlayCounts, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( PlayCounts.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_playcount IN " ) + ArrayIntToStrList( PlayCounts );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumArtistsSongs( const wxArrayInt &albumartists, guTrackArray * tracks )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Track;
if( albumartists.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_albumartistid IN " ) + ArrayIntToStrList( albumartists );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Track = new guTrack();
FillTrackFromDb( Track, &dbRes );
tracks->Add( Track );
}
dbRes.Finalize();
}
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetComposersSongs( const wxArrayInt &Composers, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
if( Composers.Count() )
{
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "song_composerid IN " ) + ArrayIntToStrList( Composers );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
}
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetPlayListType( const int plid )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
query = wxString::Format( wxT( "SELECT playlist_type FROM playlists WHERE playlist_id = %u LIMIT 1;" ), plid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetRandomTracks( guTrackArray * tracks, const int count, const int rndmode,
const int allowplaylist, const int denyplaylist )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Track;
wxString AllowPlQuery = wxEmptyString;
wxString DenyPlQuery = wxEmptyString;
//guLogMessage( wxT( "GetRandomTracks... %i %i %i" ), rndmode, allowplaylist, denyplaylist );
AllowPlQuery = GetPlayListQuery( allowplaylist );
DenyPlQuery = GetPlayListQuery( denyplaylist );
wxString Filters = wxEmptyString;
if( !AllowPlQuery.IsEmpty() )
{
Filters += wxT( "WHERE song_id IN ( " ) + AllowPlQuery + wxT( " ) " );
}
if( !DenyPlQuery.IsEmpty() )
{
Filters += Filters.IsEmpty() ? wxT( "WHERE " ) : wxT( "AND " );
Filters += wxT( "song_id NOT IN ( " ) + DenyPlQuery + wxT( " ) " );
}
if( rndmode == guRANDOM_MODE_TRACK )
{
query = GU_TRACKS_QUERYSTR + Filters;
query += wxString::Format( wxT( " ORDER BY RANDOM() LIMIT %u;" ), count );
}
else //if( rndmode == guRANDOM_MODE_ALBUM )
{
int AlbumId = 0;
query = wxT( "SELECT song_albumid FROM songs " ) + Filters;
query += wxT( " ORDER BY RANDOM() LIMIT 1;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
AlbumId = dbRes.GetInt( 0 );
}
dbRes.Finalize();
query = GU_TRACKS_QUERYSTR + wxString::Format( wxT( "WHERE song_albumid = %i" ), AlbumId );
query += wxT( " ORDER BY song_disk, song_number, song_filename" );
//query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
}
//guLogMessage( wxT( "GetRandomTracks:\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Track = new guTrack();
FillTrackFromDb( Track, &dbRes );
Track->m_TrackMode = guTRACK_MODE_RANDOM;
tracks->Add( Track );
}
dbRes.Finalize();
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
const wxString guDbLibrary::GetArtistName( const int ArtistId )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString RetVal = wxEmptyString;
query = wxString::Format( wxT( "SELECT song_artist FROM songs WHERE song_artistid = %u LIMIT 1;" ), ArtistId );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetString( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetArtistId( wxString &artistname, bool create )
{
if( m_LastArtist == artistname )
{
return m_LastArtistId;
}
// TODO Add a Lock
wxString query;
wxSQLite3ResultSet dbRes;
m_LastArtist = artistname;
query = wxString::Format( wxT( "SELECT song_artistid FROM songs " \
"WHERE song_artist = '%s' LIMIT 1;" ),
escape_query_str( artistname ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return m_LastArtistId = dbRes.GetInt( 0 );
}
else if( create )
{
query = wxT( "SELECT MAX(song_artistid) FROM songs" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return m_LastArtistId = dbRes.GetInt( 0 ) + 1;
}
else
{
return m_LastArtistId = 1;
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumArtistId( wxString &albumartist, bool create )
{
if( m_LastAlbumArtist == albumartist )
{
return m_LastAlbumArtistId;
}
// TODO Add a Lock
wxString query;
wxSQLite3ResultSet dbRes;
m_LastAlbumArtist = albumartist;
query = wxString::Format( wxT( "SELECT song_albumartistid FROM songs " \
"WHERE song_albumartist = '%s' LIMIT 1;" ),
escape_query_str( albumartist ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return m_LastAlbumArtistId = dbRes.GetInt( 0 );
}
else if( create )
{
query = wxT( "SELECT MAX(song_albumartistid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return m_LastAlbumArtistId = dbRes.GetInt( 0 ) + 1;
}
else
{
return m_LastAlbumArtistId = 1;
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::FindArtist( const wxString &Artist )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT song_artistid FROM songs WHERE song_artist = '%s' LIMIT 1;" ),
escape_query_str( Artist ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetInt( 0 );
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::FindAlbum( const wxString &Artist, const wxString &Album )
{
wxString query;
wxSQLite3ResultSet dbRes;
int ArtistId = FindArtist( Artist );
if( ArtistId != wxNOT_FOUND )
{
query = wxString::Format( wxT( "SELECT song_albumid FROM songs WHERE " \
"song_artistid = %d AND song_album = '%s' LIMIT 1;" ),
ArtistId,
escape_query_str( Album ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetInt( 0 );
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::FindTrack( const wxString &Artist, const wxString &Name )
{
wxString query;
wxSQLite3ResultSet dbRes;
int ArtistId = FindArtist( Artist );
if( ArtistId != wxNOT_FOUND )
{
query = wxString::Format( wxT( "SELECT song_id FROM songs WHERE " )\
wxT( "song_artistid = %d AND song_name = '%s' LIMIT 1;" ),
ArtistId,
escape_query_str( Name ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetInt( 0 );
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetTrackIndex( const int trackid )
{
wxString query;
wxSQLite3ResultSet dbRes;
int Index = 0;
query = wxT( "SELECT song_id FROM songs " );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
if( dbRes.GetInt( 0 ) == trackid )
return Index;
Index++;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
guTrack * guDbLibrary::FindSong( const wxString &artist, const wxString &trackname,
const int filterallow, const int filterdeny )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * RetVal = NULL;
wxString ArtistName = artist;
wxString TrackName = trackname;
wxString Filters = wxEmptyString;
wxString AllowPlQuery = GetPlayListQuery( filterallow );
if( !AllowPlQuery.IsEmpty() )
{
Filters += wxT( "WHERE song_id IN ( " ) + AllowPlQuery + wxT( " ) " );
}
wxString DenyPlQuery = GetPlayListQuery( filterdeny );
if( !DenyPlQuery.IsEmpty() )
{
Filters += Filters.IsEmpty() ? wxT( "WHERE " ) : wxT( "AND " );
Filters += wxT( "song_id NOT IN ( " ) + DenyPlQuery + wxT( " ) " );
}
escape_query_str( &ArtistName );
escape_query_str( &TrackName );
query = GU_TRACKS_QUERYSTR;
query += Filters;
if( !Filters.IsEmpty() )
query += wxT( " AND" );
else
query += wxT( " WHERE" );
query += wxString::Format( wxT( " song_artist = '%s' AND song_name = '%s' LIMIT 1;" ), ArtistName.c_str(), TrackName.c_str() );
//guLogMessage( wxT( "FindSong:\n%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = new guTrack();
FillTrackFromDb( RetVal, &dbRes );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::FindTrackFile( const wxString &filename, guTrack * track )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
wxString Path = wxPathOnly( filename );
if( !Path.EndsWith( wxT( "/" ) ) )
Path += '/';
escape_query_str( &Path );
// query = wxString::Format( wxT( "SELECT path_id FROM paths WHERE path_value = '%s' LIMIT 1" ), Path.c_str() );
//
// dbRes = ExecuteQuery( query );
//
// if( dbRes.NextRow() )
// {
// PathId = dbRes.GetInt( 0 );
// }
// dbRes.Finalize();
//
// if( PathId > 0 )
// {
// Path = filename.AfterLast( '/' );
// escape_query_str( &Path );
query = GU_TRACKS_QUERYSTR +
wxString::Format( wxT( " WHERE song_path = '%s' AND song_filename = '%s' LIMIT 1;" ),
Path.c_str(),
escape_query_str( filename.AfterLast( '/' ) ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
if( track )
{
FillTrackFromDb( track, &dbRes );
}
}
dbRes.Finalize();
// }
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::FindTrackId( const int trackid, guTrack * track )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
query = GU_TRACKS_QUERYSTR + wxString::Format( wxT( " WHERE song_id = %u LIMIT 1;" ), trackid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
if( track )
{
FillTrackFromDb( track, &dbRes );
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString GetSongsDBNamesSQL( const int order )
{
wxString query = wxEmptyString;
//
switch( order )
{
case guTRACKS_ORDER_YEAR :
case guTRACKS_ORDER_DISK :
//query += wxT( ",albums WHERE song_albumid = album_id " );
break;
case guTRACKS_ORDER_ARTIST :
//query += wxT( ",artists,albums WHERE song_artistid = artist_id AND song_albumid = album_id " );
break;
case guTRACKS_ORDER_ALBUM :
//query += wxT( ",albums WHERE song_albumid = album_id " );
break;
case guTRACKS_ORDER_GENRE :
//query += wxT( ",genres WHERE song_genreid = genre_id " );
break;
case guTRACKS_ORDER_COMPOSER :
//query += wxT( ",composers WHERE song_composerid = composer_id " );
break;
// case guTRACKS_ORDER_TITLE :
// case guTRACKS_ORDER_NUMBER :
// case guTRACKS_ORDER_LENGTH :
// case guTRACKS_ORDER_RATING :
// case guTRACKS_ORDER_BITRATE :
// case guTRACKS_ORDER_PLAYCOUNT :
// case guTRACKS_ORDER_LASTPLAY :
// case guTRACKS_ORDER_ADDEDDATE :
// break;
default:
break;
}
return query;
}
// -------------------------------------------------------------------------------- //
wxString GetSongsSortSQL( const int order, const bool orderdesc )
{
wxString query = wxT( " ORDER BY " );
//
switch( order )
{
case guTRACKS_ORDER_TITLE :
query += wxT( "song_name" );
break;
case guTRACKS_ORDER_ARTIST :
query += wxT( "song_artist" );
break;
case guTRACKS_ORDER_ALBUMARTIST :
query += wxT( "song_albumartist" );
break;
case guTRACKS_ORDER_ALBUM :
query += wxT( "song_album" );
break;
case guTRACKS_ORDER_GENRE :
query += wxT( "song_genre" );
break;
case guTRACKS_ORDER_COMPOSER :
//query += wxT( "composer_name " );
query += wxT( "song_composer" );
break;
case guTRACKS_ORDER_DISK :
query += wxT( "song_disk" );
break;
case guTRACKS_ORDER_NUMBER :
query += wxT( "song_number" );
break;
case guTRACKS_ORDER_LENGTH :
query += wxT( "song_length" );
break;
case guTRACKS_ORDER_YEAR :
query += wxT( "song_year" );
break;
case guTRACKS_ORDER_RATING :
query += wxT( "song_rating" );
break;
case guTRACKS_ORDER_BITRATE :
query += wxT( "song_bitrate" );
break;
case guTRACKS_ORDER_PLAYCOUNT :
query += wxT( "song_playcount" );
break;
case guTRACKS_ORDER_LASTPLAY :
query += wxT( "song_lastplay" );
break;
case guTRACKS_ORDER_ADDEDDATE :
query += wxT( "song_addedtime" );
break;
case guTRACKS_ORDER_FORMAT :
query += wxT( "song_format" );
break;
case guTRACKS_ORDER_FILEPATH :
query += wxT( "song_path" );
break;
default :
return wxEmptyString;
}
//
if( orderdesc )
query += wxT( " DESC" );
switch( order )
{
case guTRACKS_ORDER_DISK :
query += wxT( ",song_albumid,song_number " );
break;
case guTRACKS_ORDER_COMPOSER :
query += wxT( ",song_artist,song_album,song_disk,song_albumid,song_number " );
break;
case guTRACKS_ORDER_ARTIST :
case guTRACKS_ORDER_ALBUMARTIST :
query += wxT( ",song_album,song_disk,song_albumid,song_number " );
break;
case guTRACKS_ORDER_ALBUM :
query += wxT( ",song_disk,song_albumid,song_number " );
break;
case guTRACKS_ORDER_YEAR :
query += wxT( ",song_album,song_disk,song_albumid,song_number " );
break;
case guTRACKS_ORDER_ADDEDDATE :
query += wxT( ",song_album,song_disk,song_albumid,song_number " );
break;
default:
break;
}
//
return query;
}
// -------------------------------------------------------------------------------- //
bool guDbLibrary::GetSong( const int songid, guTrack * song )
{
bool RetVal = false;
wxString query;
wxSQLite3ResultSet dbRes;
query = GU_TRACKS_QUERYSTR;
query += wxString::Format( wxT( "WHERE song_id = %i LIMIT 1;" ), songid );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
FillTrackFromDb( song, &dbRes );
RetVal = true;
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongs( const wxArrayInt &SongIds, guTrackArray * Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
query = GU_TRACKS_QUERYSTR;
//query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "WHERE song_id IN " ) + ArrayIntToStrList( SongIds );
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
//guLogMessage( wxT( "%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
wxString inline GetTreeViewFilterEntrySql( const guTreeViewFilterEntry &filterentry )
{
wxString RetVal = wxT( "(" );
int Count = filterentry.Count();
for( int Index = 0; Index < Count; Index++ )
{
switch( filterentry[ Index ].m_Type )
{
case guLIBRARY_ELEMENT_GENRES :
RetVal += wxT( "song_genreid=" );
break;
case guLIBRARY_ELEMENT_ARTISTS :
RetVal += wxT( "song_artistid=" );
break;
case guLIBRARY_ELEMENT_COMPOSERS :
RetVal += wxT( "song_composerid=" );
break;
case guLIBRARY_ELEMENT_ALBUMARTISTS :
RetVal += wxT( "song_albumartistid=" );
break;
case guLIBRARY_ELEMENT_ALBUMS :
RetVal += wxT( "song_albumid=" );
break;
case guLIBRARY_ELEMENT_YEARS :
RetVal += wxT( "song_year=" );
break;
case guLIBRARY_ELEMENT_RATINGS :
RetVal += wxT( "song_rating=" );
break;
case guLIBRARY_ELEMENT_PLAYCOUNT :
RetVal += wxT( "song_playcount=" );
break;
}
RetVal += wxString::Format( wxT( "%i AND " ), filterentry[ Index ].m_Id );
}
RetVal.RemoveLast( 4 );
RetVal += wxT( ")" );
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString inline GetTreeViewFilterArraySql( const guTreeViewFilterArray &filterarray )
{
wxString RetVal = wxT( "(" );
int Count = filterarray.Count();
for( int Index = 0; Index < Count; Index++ )
{
RetVal += GetTreeViewFilterEntrySql( filterarray[ Index ] );
RetVal += wxT( "OR " );
}
RetVal.RemoveLast( 3 );
RetVal += wxT( ")" );
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetSongsCounters( const guTreeViewFilterArray &filters, const wxArrayString &textfilters, wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
if( !filters.Count() )
{
* count = 0;
* len = 0;
* size = 0;
return;
}
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT COUNT(), SUM(song_length), SUM(song_filesize) FROM songs " );
query += wxT( "WHERE " ) + GetTreeViewFilterArraySql( filters );
if( textfilters.Count() )
{
query += wxT( " AND " ) + TextFilterToSQL( textfilters );
}
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
* count = dbRes.GetInt64( 0 );
* len = dbRes.GetInt64( 1 );
* size = dbRes.GetInt64( 2 );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongs( const guTreeViewFilterArray &filters, guTrackArray * Songs, const wxArrayString &textfilters, const int order, const bool orderdesc )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
query = GU_TRACKS_QUERYSTR;
query += wxT( "WHERE " ) + GetTreeViewFilterArraySql( filters );
if( textfilters.Count() )
{
query += wxT( " AND " ) + TextFilterToSQL( textfilters );
}
query += GetSongsSortSQL( order, orderdesc );
//guLogMessage( wxT( "%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongsCount( void )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT COUNT(song_id) FROM songs " );
//query += GetSongsDBNamesSQL( m_TracksOrder );
if( GetFiltersCount() )
{
//query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_SONGS );
}
// query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
//guLogMessage( wxT( "%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetInt( 0 );
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongs( guTrackArray * Songs, const int start, const int end )
{
wxString query;
wxSQLite3ResultSet dbRes;
guTrack * Song;
query = GU_TRACKS_QUERYSTR;
//query += GetSongsDBNamesSQL( m_TracksOrder );
if( GetFiltersCount() )
{
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += FiltersSQL( guLIBRARY_FILTER_SONGS );
}
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
query += wxString::Format( wxT( " LIMIT %i, %i " ), start, end - start + 1 );
//guLogMessage( wxT( "%s" ), query.c_str() );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
Song = new guTrack();
FillTrackFromDb( Song, &dbRes );
Songs->Add( Song );
}
dbRes.Finalize();
return Songs->Count();
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetSongsId( const int start )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT song_id FROM songs " );
if( GetFiltersCount() )
{
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += FiltersSQL( guLIBRARY_FILTER_SONGS );
}
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
query += wxString::Format( wxT( " LIMIT %i, 1 " ), start );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetInt( 0 );
}
return 0;
}
// -------------------------------------------------------------------------------- //
wxString guDbLibrary::GetSongsName( const int start )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT song_name FROM songs " );
if( GetFiltersCount() )
{
query += ( query.Find( wxT( "WHERE" ) ) == wxNOT_FOUND ) ? wxT( "WHERE " ) : wxT( "AND " );
query += FiltersSQL( guLIBRARY_FILTER_SONGS );
}
query += GetSongsSortSQL( m_TracksOrder, m_TracksOrderDesc );
query += wxString::Format( wxT( " LIMIT %i, 1 " ), start );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return dbRes.GetString( 0 );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::GetTracksCounters( wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT COUNT(), SUM(song_length), SUM(song_filesize) FROM songs " );
if( GetFiltersCount() )
{
query += wxT( "WHERE " ) + FiltersSQL( guLIBRARY_FILTER_SONGS );
}
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
* count = dbRes.GetInt64( 0 );
* len = dbRes.GetInt64( 1 );
* size = dbRes.GetInt64( 2 );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::DeleteLibraryTracks( const guTrackArray * tracks, const bool createdeleted )
{
wxArrayInt Tracks;
wxArrayInt Covers;
int Count = tracks->Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = tracks->Item( Index );
Tracks.Add( Track.m_SongId );
if( createdeleted )
{
FindDeletedFile( Track.m_FileName, true );
}
}
CleanItems( Tracks, Covers );
}
// -------------------------------------------------------------------------------- //
bool guDbLibrary::FindDeletedFile( const wxString &file, const bool create )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT delete_id FROM deleted WHERE delete_path = '%s' LIMIT 1;" ),
escape_query_str( file ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
return true;
}
if( create )
{
query = wxT( "INSERT INTO deleted( delete_id, delete_path, delete_date ) " );
query += wxString::Format( wxT( "VALUES( NULL, '%s', %lu )" ),
escape_query_str( file ).c_str(), wxDateTime::GetTimeNow() );
ExecuteUpdate( query );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDbLibrary::GetAlbumInfo( const int AlbumId, wxString * AlbumName, wxString * ArtistName, wxString * AlbumPath )
{
wxString query;
wxSQLite3ResultSet dbRes;
bool RetVal = false;
query = wxString::Format( wxT( "SELECT DISTINCT song_album, song_albumartist, song_artist, song_path " \
"FROM songs WHERE song_albumid = %u LIMIT 1" ), AlbumId );
//guLogMessage( query );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
if( AlbumName )
* AlbumName = dbRes.GetString( 0 );
if( ArtistName )
{
* ArtistName = dbRes.GetString( 1 );
if( ArtistName->IsEmpty() )
* ArtistName = dbRes.GetString( 2 );
}
if( AlbumPath )
* AlbumPath = dbRes.GetString( 3 );
RetVal = true;
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetAlbumCoverId( const int AlbumId )
{
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = wxNOT_FOUND;
query = wxString::Format ( wxT( "SELECT song_coverid " ) \
wxT( "FROM songs " ) \
wxT( "WHERE song_albumid = %u LIMIT 1;" ), AlbumId );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
guArrayListItems guDbLibrary::GetArtistsLabels( const wxArrayInt &Artists )
{
wxString query;
wxSQLite3ResultSet dbRes;
guArrayListItems RetVal;
guArrayListItem * CurItem = NULL;
int Id;
int count = Artists.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
Id = Artists[ index ];
RetVal.Add( new guArrayListItem( Id ) );
}
query = wxT( "SELECT settag_artistid, settag_tagid FROM settags " ) \
wxT( "WHERE settag_artistid IN " ) + ArrayIntToStrList( Artists );
query += wxT( " ORDER BY settag_artistid,settag_tagid;" );
dbRes = ExecuteQuery( query );
int index = 0;
CurItem = &RetVal[ index ];
while( dbRes.NextRow() )
{
Id = dbRes.GetInt( 0 );
if( CurItem->GetId() != Id )
{
index = 0;
while( CurItem->GetId() != Id )
{
CurItem = &RetVal[ index ];
index++;
}
}
CurItem->AddData( dbRes.GetInt( 1 ) );
}
dbRes.Finalize();
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
guArrayListItems guDbLibrary::GetAlbumsLabels( const wxArrayInt &Albums )
{
wxString query;
wxSQLite3ResultSet dbRes;
guArrayListItems RetVal;
guArrayListItem * CurItem = NULL;
int Id;
int count = Albums.Count();
for( int index = 0; index < count; index++ )
{
Id = Albums[ index ];
RetVal.Add( new guArrayListItem( Id ) );
}
query = wxT( "SELECT settag_albumid, settag_tagid FROM settags " ) \
wxT( "WHERE settag_albumid IN " ) + ArrayIntToStrList( Albums );
query += wxT( " ORDER BY settag_albumid,settag_tagid;" );
dbRes = ExecuteQuery( query );
int index = 0;
CurItem = &RetVal[ index ];
while( dbRes.NextRow() )
{
Id = dbRes.GetInt( 0 );
if( CurItem->GetId() != Id )
{
index = 0;
while( CurItem->GetId() != Id )
{
CurItem = &RetVal[ index ];
index++;
}
}
CurItem->AddData( dbRes.GetInt( 1 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
guArrayListItems guDbLibrary::GetSongsLabels( const wxArrayInt &Songs )
{
wxString query;
wxSQLite3ResultSet dbRes;
guArrayListItems RetVal;
guArrayListItem * CurItem = NULL;
int Id;
int count = Songs.Count();
for( int index = 0; index < count; index++ )
{
Id = Songs[ index ];
RetVal.Add( new guArrayListItem( Id ) );
}
query = wxT( "SELECT settag_songid, settag_tagid FROM settags " ) \
wxT( "WHERE settag_songid IN " ) + ArrayIntToStrList( Songs );
query += wxT( " ORDER BY settag_songid,settag_tagid;" );
dbRes = ExecuteQuery( query );
//guLogMessage( query );
int index = 0;
CurItem = &RetVal[ index ];
while( dbRes.NextRow() )
{
Id = dbRes.GetInt( 0 );
if( CurItem->GetId() != Id )
{
index = 0;
while( CurItem->GetId() != Id )
{
CurItem = &RetVal[ index ];
index++;
}
}
CurItem->AddData( dbRes.GetInt( 1 ) );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetArtistsLabels( const wxArrayInt &Artists, const wxArrayInt &Labels )
{
wxString query;
int ArIndex;
int ArCount;
int LaIndex;
int LaCount;
query = wxT( "DELETE FROM settags " ) \
wxT( "WHERE settag_artistid IN " ) + ArrayIntToStrList( Artists );
ExecuteUpdate( query );
ArCount = Artists.Count();
LaCount = Labels.Count();
for( ArIndex = 0; ArIndex < ArCount; ArIndex++ )
{
for( LaIndex = 0; LaIndex < LaCount; LaIndex++ )
{
query = wxString::Format( wxT( "INSERT INTO settags( settag_tagid, settag_artistid ) "\
"VALUES( %u, %u );" ), Labels[ LaIndex ], Artists[ ArIndex ] );
ExecuteUpdate( query );
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetAlbumsLabels( const wxArrayInt &Albums, const wxArrayInt &Labels )
{
wxString query;
int AlIndex;
int AlCount;
int TaIndex;
int TaCount;
query = wxT( "DELETE FROM settags " ) \
wxT( "WHERE settag_albumid IN " ) + ArrayIntToStrList( Albums );
ExecuteUpdate( query );
AlCount = Albums.Count();
for( AlIndex = 0; AlIndex < AlCount; AlIndex++ )
{
TaCount = Labels.Count();
for( TaIndex = 0; TaIndex < TaCount; TaIndex++ )
{
query = wxString::Format( wxT( "INSERT INTO settags( settag_tagid, settag_albumid ) "\
"VALUES( %u, %u );" ), Labels[ TaIndex ], Albums[ AlIndex ] );
ExecuteUpdate( query );
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetSongsLabels( const wxArrayInt &Songs, const wxArrayInt &Labels )
{
wxString query;
int SoIndex;
int SoCount;
int LaIndex;
int LaCount;
query = wxT( "DELETE FROM settags " ) \
wxT( "WHERE settag_songid IN " ) + ArrayIntToStrList( Songs );
ExecuteUpdate( query );
SoCount = Songs.Count();
LaCount = Labels.Count();
for( SoIndex = 0; SoIndex < SoCount; SoIndex++ )
{
for( LaIndex = 0; LaIndex < LaCount; LaIndex++ )
{
query = wxString::Format( wxT( "INSERT INTO settags( settag_tagid, settag_songid ) "\
"VALUES( %u, %u );" ), Labels[ LaIndex ], Songs[ SoIndex ] );
ExecuteUpdate( query );
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateArtistsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
guTrackArray Songs;
guTrack * Song;
wxString ArtistLabelStr;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ArIndex;
int ArCount = labelsets.Count();
for( ArIndex = 0; ArIndex < ArCount; ArIndex++ )
{
wxArrayInt ArLabels = labelsets[ ArIndex ].GetData();
int Count = ArLabels.Count();
ArtistLabelStr.Empty();
for( int Index = 0; Index < Count; Index++ )
{
ArtistLabelStr += guListItemsGetName( LaItems, ArLabels[ Index ] );
ArtistLabelStr += wxT( "|" );
}
if( !ArtistLabelStr.IsEmpty() )
ArtistLabelStr.RemoveLast( 1 );
//guLogMessage( wxT( "Artist Labels : '%s'" ), ArtistLabelStr.c_str() );
// Update the Database
wxArrayInt Artists;
Artists.Add( labelsets[ ArIndex ].GetId() );
SetArtistsLabels( Artists, ArLabels );
if( m_MediaViewer->GetEmbeddMetadata() )
{
// Get the affected tracks
GetArtistsSongs( Artists, &Songs );
Count = Songs.Count();
for( int Index = 0; Index < Count; Index++ )
{
Song = &Songs[ Index ];
if( wxFileExists( Song->m_FileName ) )
{
guTagInfo * TagInfo;
TagInfo = guGetTagInfoHandler( Song->m_FileName );
if( !TagInfo )
continue;
TagInfo->Read();
TagInfo->m_ArtistLabelsStr = ArtistLabelStr;
TagInfo->Write( guTRACK_CHANGED_DATA_LABELS );
delete TagInfo;
}
else
{
guLogError( wxT( "The file '%s' could not be found" ), Song->m_FileName.c_str() );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateAlbumsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
guTrackArray Songs;
guTrack * Song;
wxString AlbumLabelStr;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ItemIndex;
int ItemCount = labelsets.Count();
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
wxArrayInt ItemLabels = labelsets[ ItemIndex ].GetData();
int Count = ItemLabels.Count();
AlbumLabelStr.Empty();
for( int Index = 0; Index < Count; Index++ )
{
AlbumLabelStr += guListItemsGetName( LaItems, ItemLabels[ Index ] ) + wxT( "|" );
}
if( !AlbumLabelStr.IsEmpty() )
AlbumLabelStr.RemoveLast( 1 );
guLogMessage( wxT( "Album Labels : '%s'" ), AlbumLabelStr.c_str() );
// Update the Database
wxArrayInt ItemIds;
ItemIds.Add( labelsets[ ItemIndex ].GetId() );
SetAlbumsLabels( ItemIds, ItemLabels );
if( m_MediaViewer->GetEmbeddMetadata() )
{
// Get the affected tracks
GetAlbumsSongs( ItemIds, &Songs );
Count = Songs.Count();
for( int Index = 0; Index < Count; Index++ )
{
Song = &Songs[ Index ];
if( wxFileExists( Song->m_FileName ) )
{
guTagInfo * TagInfo;
TagInfo = guGetTagInfoHandler( Song->m_FileName );
if( !TagInfo )
continue;
TagInfo->Read();
TagInfo->m_AlbumLabelsStr = AlbumLabelStr;
TagInfo->Write( guTRACK_CHANGED_DATA_LABELS );
delete TagInfo;
}
else
{
guLogError( wxT( "The file '%s' could not be found" ), Song->m_FileName.c_str() );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateSongsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
guTrackArray Songs;
guTrack * Song;
wxString TrackLabelStr;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ItemIndex;
int ItemCount = labelsets.Count();
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
wxArrayInt ItemLabels = labelsets[ ItemIndex ].GetData();
int Count = ItemLabels.Count();
TrackLabelStr.Empty();
for( int Index = 0; Index < Count; Index++ )
{
TrackLabelStr += guListItemsGetName( LaItems, ItemLabels[ Index ] ) + wxT( "|" );
}
if( !TrackLabelStr.IsEmpty() )
TrackLabelStr.RemoveLast( 1 );
//guLogMessage( wxT( "Artist Labels : '%s'" ), ArtistLabelStr.c_str() );
// Update the Database
wxArrayInt ItemIds;
ItemIds.Add( labelsets[ ItemIndex ].GetId() );
SetSongsLabels( ItemIds, ItemLabels );
if( m_MediaViewer->GetEmbeddMetadata() )
{
// Get the affected tracks
GetSongs( ItemIds, &Songs );
Count = Songs.Count();
for( int Index = 0; Index < Count; Index++ )
{
Song = &Songs[ Index ];
if( Song->m_Offset )
continue;
if( wxFileExists( Song->m_FileName ) )
{
guTagInfo * TagInfo;
TagInfo = guGetTagInfoHandler( Song->m_FileName );
if( !TagInfo )
continue;
TagInfo->Read();
TagInfo->m_TrackLabelsStr = TrackLabelStr;
TagInfo->Write( guTRACK_CHANGED_DATA_LABELS );
delete TagInfo;
}
else
{
guLogError( wxT( "The file '%s' could not be found" ), Song->m_FileName.c_str() );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void inline RemoveLabel( wxString * labelstr, const wxString * labelname, const wxString * newname )
{
if( labelstr->IsEmpty() )
return;
if( labelstr->Replace( wxT( "|" + ( * labelname ) ), * newname ) )
return;
if( labelstr->Replace( ( * labelname ) + wxT( "|" ), * newname ) )
return;
labelstr->Replace( ( * labelname ), * newname );
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateSongLabel( const guTrack &track, const wxString &label, const wxString &newname )
{
if( wxFileExists( track.m_FileName ) )
{
guTagInfo * TagInfo = guGetTagInfoHandler( track.m_FileName );
if( !TagInfo )
return;
TagInfo->Read();
RemoveLabel( &TagInfo->m_TrackLabelsStr, &label, &newname );
RemoveLabel( &TagInfo->m_ArtistLabelsStr, &label, &newname );
RemoveLabel( &TagInfo->m_AlbumLabelsStr, &label, &newname );
TagInfo->Write( guTRACK_CHANGED_DATA_LABELS );
delete TagInfo;
}
else
{
guLogError( wxT( "The file '%s' could not be found" ), track.m_FileName.c_str() );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateSongsLabel( const guTrackArray &tracks, const wxString &label, const wxString &newname )
{
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
UpdateSongLabel( tracks[ Index ], label, newname );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetTrackRating( const int songid, const int rating, const bool writetags )
{
wxString query;
query = wxString::Format( wxT( "UPDATE songs SET song_rating = %u WHERE song_id = %u;" ),
rating, songid );
ExecuteUpdate( query );
if( writetags )
{
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetTracksRating( const wxArrayInt &songids, const int rating, const bool writetags )
{
wxString query;
if( songids.Count() )
{
query = wxString::Format( wxT( "UPDATE songs SET song_rating = %u WHERE song_id IN " ),
rating );
query += ArrayIntToStrList( songids );
ExecuteUpdate( query );
if( writetags )
{
}
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetTracksRating( const guTrackArray * tracks, const int rating, const bool writetags )
{
int Count = tracks->Count();
if( Count )
{
wxArrayInt TrackIds;
for( int Index = 0; Index < Count; Index++ )
{
TrackIds.Add( tracks->Item( Index ).m_SongId );
}
SetTracksRating( TrackIds, rating, writetags );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::SetTrackPlayCount( const int songid, const int playcount, const bool writetags )
{
wxString query;
query = wxString::Format( wxT( "UPDATE songs SET song_playcount = %u, song_lastplay = %lu WHERE song_id = %u;" ),
playcount, wxDateTime::GetTimeNow(), songid );
ExecuteUpdate( query );
if( writetags )
{
}
}
// -------------------------------------------------------------------------------- //
int guDbLibrary::GetEmptyCovers( guCoverInfos &coverinfos )
{
wxString query;
wxSQLite3ResultSet dbRes;
query = wxT( "SELECT DISTINCT song_albumid, song_album, song_artist, song_path " \
"FROM songs WHERE song_coverid ISNULL OR song_coverid < 1 GROUP BY song_albumid" );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
coverinfos.Add( new guCoverInfo( dbRes.GetInt( 0 ), dbRes.GetString( 1 ), dbRes.GetString( 2 ), dbRes.GetString( 3 ) ) );
}
dbRes.Finalize();
return coverinfos.Count();
}
// -------------------------------------------------------------------------------- //
// AudioScrobbler Functions
// -------------------------------------------------------------------------------- //
//audioscs(
// audiosc_id INTEGER PRIMARY KEY AUTOINCREMENT,
// audiosc_artist VARCHAR(255),
// audiosc_album varchar(255),
// audiosc_track varchar(255),
// audiosc_playedtime INTEGER,
// audiosc_source char(1),
// audiosc_ratting char(1),
// audiosc_len INTEGER,
// audiosc_tracknum INTEGER,
// audiosc_mbtrackid INTEGER
// -------------------------------------------------------------------------------- //
bool guDbLibrary::AddCachedPlayedSong( const guCurrentTrack &Song )
{
wxString query;
wxSQLite3ResultSet dbRes;
wxString Title = Song.m_SongName;
wxString Artist = Song.m_ArtistName;
wxString Album = Song.m_AlbumName;
char Source;
if( Song.m_Type == guTRACK_TYPE_RADIOSTATION )
{
Source = 'R';
}
else
{
switch( Song.m_TrackMode )
{
case guTRACK_MODE_SMART :
Source = 'L';
break;
case guTRACK_MODE_USER :
Source = 'P';
break;
case guTRACK_MODE_RANDOM :
Source = 'S';
break;
default :
Source = 'U';
break;
}
}
char Rating;
switch( Song.m_ASRating )
{
case guAS_RATING_LOVE :
Rating = 'L';
break;
case guAS_RATING_BAN :
Rating = 'B';
break;
case guAS_RATING_SKIP :
Rating = 'S';
break;
//case guAS_RATING_NONE :
default :
Rating = ' ';
break;
}
escape_query_str( &Title );
escape_query_str( &Artist );
escape_query_str( &Album );
int PlayTime = Song.m_PlayTime / 1000;
int TrackLength = Song.m_Length / 1000;
if( Song.m_Type == guTRACK_TYPE_RADIOSTATION )
{
PlayTime = 180;
TrackLength = 180;
}
guLogMessage( wxT( "Adding track at %lu played %u mseconds" ), wxGetUTCTime(), PlayTime );
query = wxString::Format( wxT( "INSERT into audioscs( audiosc_id, audiosc_artist, " \
"audiosc_album, audiosc_track, audiosc_playedtime, audiosc_source, " \
"audiosc_ratting, audiosc_len, audiosc_tracknum, audiosc_mbtrackid) " \
"VALUES( NULL, '%s', '%s', '%s', %lu, '%c', '%c', %u, %i, %u );" ),
Artist.c_str(),
Album.c_str(),
Title.c_str(),
wxGetUTCTime() - PlayTime,
Source,
Rating,
TrackLength,
Song.m_Number,
0 );
//guLogMessage( query );
return ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
guAS_SubmitInfoArray guDbLibrary::GetCachedPlayedSongs( int MaxCount )
{
wxString query;
wxSQLite3ResultSet dbRes;
guAS_SubmitInfoArray RetVal;
guAS_SubmitInfo * PlayedSong;
query = wxString::Format( wxT( "SELECT audiosc_id, audiosc_artist, audiosc_album, audiosc_track, " \
"audiosc_playedtime, audiosc_source, audiosc_ratting, audiosc_len, " \
"audiosc_tracknum, audiosc_mbtrackid " \
"FROM audioscs ORDER BY audiosc_playedtime LIMIT %u" ), MaxCount );
dbRes = ExecuteQuery( query );
while( dbRes.NextRow() )
{
PlayedSong = new guAS_SubmitInfo();
PlayedSong->m_Id = dbRes.GetInt( 0 );
PlayedSong->m_ArtistName = dbRes.GetString( 1 );
PlayedSong->m_AlbumName = dbRes.GetString( 2 );
PlayedSong->m_TrackName = dbRes.GetString( 3 );
PlayedSong->m_PlayedTime = dbRes.GetInt( 4 );
PlayedSong->m_Source = dbRes.GetString( 5 )[ 0 ];
PlayedSong->m_Rating = dbRes.GetString( 6 )[ 0 ];
PlayedSong->m_TrackLen = dbRes.GetInt( 7 );
PlayedSong->m_TrackNum = dbRes.GetInt( 8 );
PlayedSong->m_MBTrackId = dbRes.GetInt( 9 );
RetVal.Add( PlayedSong );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guDbLibrary::DeleteCachedPlayedSongs( const guAS_SubmitInfoArray &SubmitInfo )
{
wxString query;
// wxSQLite3ResultSet dbRes;
int count = SubmitInfo.Count();
if( count )
{
query = wxT( "DELETE from audioscs WHERE audiosc_id IN (" );
for( int index = 0; index < count; index++ )
{
query += wxString::Format( wxT( "%u," ), SubmitInfo[ index ].m_Id );
}
query.RemoveLast( 1 );
query += wxT( ");" );
if( ExecuteUpdate( query ) )
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdateTrackFileName( const wxString &oldname, const wxString &newname )
{
int TrackId = FindTrackFile( oldname, NULL );
//guLogMessage( wxT( "The track %s was found with id %i" ), oldname.c_str(), TrackId );
if( TrackId )
{
wxString NewPath = wxPathOnly( newname );
if( !NewPath.EndsWith( wxT( "/" ) ) )
NewPath += wxT( "/" );
int PathId = GetPathId( NewPath );
wxString query = wxString::Format( wxT( "UPDATE songs SET song_filename = '%s', song_pathid = %i, song_path = '%s' WHERE song_id = %u;" ),
escape_query_str( newname.AfterLast( '/' ) ).c_str(),
PathId,
escape_query_str( NewPath ).c_str(),
TrackId );
//guLogMessage( wxT( "Updating file: %s" ), query.c_str() );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
void guDbLibrary::UpdatePaths( const wxString &oldpath, const wxString &newpath )
{
wxString query;
query = wxString::Format( wxT( "UPDATE songs SET song_path = replace( song_path, '%s', '%s' )" ),
escape_query_str( oldpath ).c_str(), escape_query_str( newpath ).c_str() );
//guLogMessage( wxT( "Updating path: %s" ), query.c_str() );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
| 210,823
|
C++
|
.cpp
| 5,423
| 32.782039
| 349
| 0.559705
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,554
|
DbCache.cpp
|
anonbeat_guayadeque/src/db/DbCache.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "DbCache.h"
#include "Utils.h"
#include <wx/mstream.h>
namespace Guayadeque {
guDbCache * guDbCache::m_DbCache = NULL;
// -------------------------------------------------------------------------------- //
guDbCache::guDbCache( const wxString &dbname ) : guDb( dbname )
{
wxArrayString query;
query.Add( wxT( "CREATE TABLE IF NOT EXISTS cache( cache_id INTEGER PRIMARY KEY AUTOINCREMENT, " \
"cache_key varchar, cache_data BLOB, cache_time INTEGER, " \
"cache_type INTEGER, cache_size INTEGER );" ) );
query.Add( wxT( "CREATE UNIQUE INDEX IF NOT EXISTS 'cache_id' on cache( cache_id ASC );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'cache_key' on cache( cache_key ASC );" ) );
query.Add( wxT( "CREATE INDEX IF NOT EXISTS 'cache_time' on cache( cache_time ASC );" ) );
int Count = query.Count();
for( int Index = 0; Index < Count; Index++ )
{
//guLogMessage( query[ Index ] );
ExecuteUpdate( query[ Index ] );
}
}
// -------------------------------------------------------------------------------- //
guDbCache::~guDbCache()
{
}
// -------------------------------------------------------------------------------- //
wxImage * guDbCache::GetImage( const wxString &url, wxBitmapType &imgtype, const int imgsize )
{
wxImage * Img = NULL;
wxString query;
wxSQLite3ResultSet dbRes;
const unsigned char * Data;
int DataLen = 0;
query = wxString::Format( wxT( "SELECT cache_data, cache_type FROM cache WHERE cache_key = '%s' " \
"AND cache_size = %u LIMIT 1;" ),
escape_query_str( url ).c_str(), imgsize );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
Data = dbRes.GetBlob( 0, DataLen );
imgtype = wxBitmapType( dbRes.GetInt( 1 ) );
if( DataLen )
{
wxMemoryInputStream Ins( Data, DataLen );
Img = new wxImage( Ins, imgtype );
if( Img )
{
if( !Img->IsOk() )
{
guLogMessage( wxT( "Image is not OK" ) );
delete Img;
Img = NULL;
}
}
// else
// {
// guLogMessage( wxT( "Could not create the image" ) );
// }
}
}
// else
// {
// guLogMessage( wxT( "DbCache failed '%s'" ), url.c_str() );
// }
dbRes.Finalize();
return Img;
}
// -------------------------------------------------------------------------------- //
bool guDbCache::DoSetImage( const wxString &url, wxImage * img, const wxBitmapType imgtype, const int imagesize )
{
wxMemoryOutputStream Outs;
if( img->SaveFile( Outs, imgtype ) )
{
wxSQLite3Statement stmt = m_Db->PrepareStatement( wxString::Format(
wxT( "INSERT INTO cache( cache_id, cache_key, cache_data, cache_type, cache_time, cache_size ) " \
"VALUES( NULL, '%s', ?, %u, %lu, %u );" ),
escape_query_str( url ).c_str(), ( int ) imgtype, wxDateTime::Now().GetTicks(), imagesize ) );
try {
stmt.Bind( 1, ( const unsigned char * ) Outs.GetOutputStreamBuffer()->GetBufferStart(), Outs.GetSize() );
//guLogMessage( wxT( "%s" ), stmt.GetSQL().c_str() );
stmt.ExecuteQuery();
return true;
}
catch( wxSQLite3Exception &e )
{
guLogError( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch(...)
{
guLogError( wxT( "Other exception found while updating the image in cache" ) );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDbCache::SetImage( const wxString &url, wxImage * img, const wxBitmapType imgtype )
{
wxImage TmpImg( * img );
// int Width = 150;
// int Height = 150;
// int ImageSize = guDBCACHE_TYPE_IMAGE_SIZE_BIG;
// TmpImg.Rescale( Width, Height, wxIMAGE_QUALITY_HIGH );
guImageResize( &TmpImg, 150 );
if( !DoSetImage( url, &TmpImg, imgtype, guDBCACHE_TYPE_IMAGE_SIZE_BIG ) )
return false;
TmpImg = * img;
// Width = 100;
// Height = 100;
// ImageSize = guDBCACHE_TYPE_IMAGE_SIZE_MID;
// TmpImg.Rescale( Width, Height, wxIMAGE_QUALITY_HIGH );
guImageResize( &TmpImg, 100 );
if( !DoSetImage( url, &TmpImg, imgtype, guDBCACHE_TYPE_IMAGE_SIZE_MID ) )
return false;
TmpImg = * img;
// Width = 50;
// Height = 50;
// ImageSize = guDBCACHE_TYPE_IMAGE_SIZE_TINY;
// TmpImg.Rescale( Width, Height, wxIMAGE_QUALITY_HIGH );
guImageResize( &TmpImg, 50 );
if( !DoSetImage( url, &TmpImg, imgtype, guDBCACHE_TYPE_IMAGE_SIZE_TINY ) )
return false;
// delete the expired entries but call it only 5% of the times
if( guRandom( 1000 ) < 20 )
ClearExpired();
return true;
}
// -------------------------------------------------------------------------------- //
wxString guDbCache::GetContent( const wxString &url )
{
wxString RetVal = wxEmptyString;
wxString query;
wxSQLite3ResultSet dbRes;
query = wxString::Format( wxT( "SELECT cache_data FROM cache WHERE cache_key = '%s' LIMIT 1;" ),
escape_query_str( url ).c_str() );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetString( 0 );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guDbCache::SetContent( const wxString &url, const char * str, const int len )
{
try {
wxSQLite3Statement stmt = m_Db->PrepareStatement( wxString::Format(
wxT( "INSERT INTO cache( cache_id, cache_key, cache_data, cache_type, cache_time, cache_size ) " \
"VALUES( NULL, '%s', ?, %u, %lu, %u );" ),
escape_query_str( url ).c_str(), guDBCACHE_TYPE_TEXT, wxDateTime::Now().GetTicks(), 0 ) );
stmt.Bind( 1, ( const unsigned char * ) str, len );
//guLogMessage( wxT( "%s" ), stmt.GetSQL().c_str() );
stmt.ExecuteQuery();
return true;
}
catch( wxSQLite3Exception &e )
{
guLogError( wxT( "%u: %s" ), e.GetErrorCode(), e.GetMessage().c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDbCache::SetContent( const wxString &url, const wxString &content, const int type )
{
wxString query = wxString::Format( wxT( "INSERT INTO cache( cache_id, cache_key, cache_data, " \
"cache_type, cache_time, cache_size ) VALUES( NULL, '%s', '%s', %u, %lu, %u );" ),
escape_query_str( url ).c_str(),
escape_query_str( content ).c_str(),
type,
wxDateTime::Now().GetTicks(),
0 );
ExecuteUpdate( query );
// delete the expired entries but call it only 2% of the times
if( guRandom( 1000 ) < 7 )
ClearExpired();
return true;
}
#define guDAY_SECONDS (60 * 60 * 24)
// -------------------------------------------------------------------------------- //
void guDbCache::ClearExpired( void )
{
// TODO : Clear different types with different periods
// last.fm queries are kept only 7 days
wxString query = wxString::Format( wxT( "DELETE FROM cache WHERE cache_time < %lu AND cache_type = %u" ),
wxDateTime::Now().GetTicks() - ( guDAY_SECONDS * 7 ), guDBCACHE_TYPE_TEXT );
ExecuteUpdate( query );
// Images are kept 30 days
// query = wxString::Format( wxT( "DELETE FROM cache WHERE cache_time < %lu" ), wxDateTime::Now().GetTicks() - ( guDAY_SECONDS * 30 ) );
// ExecuteUpdate( query );
query = wxString::Format( wxT( "DELETE FROM cache WHERE cache_time < %lu AND cache_type = %u" ),
wxDateTime::Now().GetTicks() - ( guDAY_SECONDS * 30 ), guDBCACHE_TYPE_LASTFM );
ExecuteUpdate( query );
query = wxString::Format( wxT( "DELETE FROM cache WHERE cache_time < %lu AND cache_type = %u" ),
wxDateTime::Now().GetTicks() - ( guDAY_SECONDS * 3 ), guDBCACHE_TYPE_TUNEIN );
ExecuteUpdate( query );
guLogMessage( wxT( "Delete expired Cache elements done" ) );
}
}
// -------------------------------------------------------------------------------- //
| 9,109
|
C++
|
.cpp
| 221
| 36.959276
| 139
| 0.55744
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,555
|
Db.cpp
|
anonbeat_guayadeque/src/db/Db.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Db.h"
#include "Utils.h"
//#define DBLIBRARY_SHOW_QUERIES 1
//#define DBLIBRARY_SHOW_TIMES 1
//#define DBLIBRARY_MIN_TIME 50
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guDb::guDb()
{
m_Db = NULL;
}
// -------------------------------------------------------------------------------- //
guDb::guDb( const wxString &dbname )
{
Open( dbname );
}
// -------------------------------------------------------------------------------- //
guDb::~guDb()
{
if( m_Db )
{
Close();
delete m_Db;
}
}
// -------------------------------------------------------------------------------- //
int guDb::Open( const wxString &dbname )
{
m_DbName = dbname;
m_Db = new wxSQLite3Database();
if( m_Db )
{
m_Db->Open( dbname );
if( m_Db->IsOpen() )
{
SetInitParams();
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------- //
int guDb::Close()
{
if( m_Db->IsOpen() )
m_Db->Close();
return 1;
}
// -------------------------------------------------------------------------------- //
wxSQLite3ResultSet guDb::ExecuteQuery( const wxString &query )
{
#ifdef DBLIBRARY_SHOW_QUERIES
guLogMessage( wxT( "ExecQuery:\n%s" ), query.c_str() );
#endif
#ifdef DBLIBRARY_SHOW_TIMES
wxLongLong time = wxGetLocalTimeMillis();
#endif
wxSQLite3ResultSet RetVal;
try {
RetVal = m_Db->ExecuteQuery( query );
}
catch( wxSQLite3Exception &e )
{
guLogError( wxT( "guDbLibrary::ExecuteQuery exception '%s'\n%u: %s" ),
query.c_str(), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch(...)
{
guLogError( wxT( "Other exception found while executing:\n'%s'" ), query.c_str() );
}
#ifdef DBLIBRARY_SHOW_TIMES
time = wxGetLocalTimeMillis() - time;
if( time > DBLIBRARY_MIN_TIME )
guLogWarning( wxT( "Query: %u ms\n%s" ), time.GetLo(), query.c_str() );
#endif
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guDb::ExecuteUpdate( const wxString &query )
{
#ifdef DBLIBRARY_SHOW_QUERIES
guLogMessage( wxT( "ExecUpdate:\n%s" ), query.c_str() );
#endif
#ifdef DBLIBRARY_SHOW_TIMES
wxLongLong time = wxGetLocalTimeMillis();
#endif
int RetVal = 0;
try {
RetVal = m_Db->ExecuteUpdate( query );
}
catch( wxSQLite3Exception &e )
{
guLogError( wxT( "guDbLibrary::ExecuteUpdate exception '%s'\n%u: %s" ),
query.c_str(), e.GetErrorCode(), e.GetMessage().c_str() );
}
catch(...)
{
guLogError( wxT( "Other exception found while executing:\n'%s'" ), query.c_str() );
}
#ifdef DBLIBRARY_SHOW_TIMES
time = wxGetLocalTimeMillis() - time;
if( time > DBLIBRARY_MIN_TIME )
guLogWarning( wxT( "Query: %u ms\n%s" ), time.GetLo(), query.c_str() );
#endif
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxSQLite3ResultSet guDb::ExecuteQuery( const wxSQLite3StatementBuffer &query )
{
return m_Db->ExecuteQuery( query );
}
// -------------------------------------------------------------------------------- //
int guDb::ExecuteUpdate( const wxSQLite3StatementBuffer &query )
{
return m_Db->ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
void guDb::SetInitParams( void )
{
wxString query;
query = wxT( "PRAGMA legacy_file_format=false; PRAGMA page_size=4096; PRAGMA cache_size=4096; PRAGMA count_changes=1; PRAGMA synchronous='OFF'; PRAGMA short_column_names=0; PRAGMA full_column_names=0;" );
//query = wxT( "PRAGMA legacy_file_format=false; PRAGMA page_size=102400; PRAGMA cache_size=204800; PRAGMA count_changes=1; PRAGMA synchronous='OFF'; PRAGMA short_column_names=0; PRAGMA full_column_names=0;" );
//query = wxT( "PRAGMA page_size=10240; PRAGMA cache_size=65536; PRAGMA count_changes=1; PRAGMA synchronous='OFF'; PRAGMA short_column_names=0; PRAGMA full_column_names=0;" );
ExecuteUpdate( query );
}
}
// -------------------------------------------------------------------------------- //
| 5,220
|
C++
|
.cpp
| 148
| 32.790541
| 212
| 0.535312
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,556
|
mpris.cpp
|
anonbeat_guayadeque/src/dbus/mpris.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "mpris.h"
#include "EventCommandIds.h"
#include "Utils.h"
namespace Guayadeque {
const char * Introspection_XML_Data_Root =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
"<node>\n"
" <node name=\"Player\"/>\n"
" <node name=\"TrackList\"/>\n"
" <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
" <method name=\"Introspect\">\n"
" <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"
" </method>\n"
" </interface>\n"
" <interface name=\"org.freedesktop.MediaPlayer\">\n"
" <method name=\"Identity\">\n"
" <arg type=\"s\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"Quit\">\n"
" </method>\n"
" <method name=\"MprisVersion\">\n"
" <arg type=\"(qq)\" direction=\"out\" />\n"
" </method>\n"
" </interface>\n"
"</node>\n"
;
const char * Introspection_XML_Data_Player =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
"<node>"
" <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
" <method name=\"Introspect\">\n"
" <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"
" </method>\n"
" </interface>\n"
" <interface name=\"org.freedesktop.MediaPlayer\">\n"
" <method name=\"Next\">\n"
" </method>\n"
" <method name=\"Prev\">\n"
" </method>\n"
" <method name=\"NextAlbum\">\n" // Non-standard
" </method>\n"
" <method name=\"PrevAlbum\">\n" // Non-standard
" </method>\n"
" <method name=\"Pause\">\n"
" </method>\n"
" <method name=\"Stop\">\n"
" </method>\n"
" <method name=\"Play\">\n"
" </method>\n"
" <method name=\"Repeat\">\n"
" <arg type=\"b\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"GetStatus\">\n"
" <arg type=\"(iiii)\" direction=\"out\"/>\n"
" </method>\n"
" <method name=\"GetMetadata\">\n"
" <arg type=\"a{sv}\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"GetCaps\">\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"VolumeSet\">\n"
" <arg type=\"i\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"VolumeGet\">\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"PositionSet\">\n"
" <arg type=\"i\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"PositionGet\">\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <signal name=\"TrackChange\">\n"
" <arg type=\"a{sv}\"/>\n"
" </signal>\n"
" <signal name=\"StatusChange\">\n"
" <arg type=\"(iiii)\"/>\n"
" </signal>\n"
" <signal name=\"CapsChange\">\n"
" <arg type=\"i\"/>\n"
" </signal>\n"
" </interface>\n"
"</node>\n"
;
const char * Introspection_XML_Data_Tracklist =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
"<node>"
" <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
" <method name=\"Introspect\">\n"
" <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"
" </method>\n"
" </interface>\n"
" <interface name=\"org.freedesktop.MediaPlayer\">\n"
" <method name=\"GetMetadata\">\n"
" <arg type=\"i\" direction=\"in\" />\n"
" <arg type=\"a{sv}\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"GetCurrentTrack\">\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"GetLength\">\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"AddTrack\">\n"
" <arg type=\"s\" direction=\"in\" />\n"
" <arg type=\"b\" direction=\"in\" />\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"DelTrack\">\n"
" <arg type=\"i\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"SetLoop\">\n"
" <arg type=\"b\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"SetRandom\">\n"
" <arg type=\"b\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"AddTracks\">\n"
" <arg type=\"as\" direction=\"in\" />\n"
" <arg type=\"b\" direction=\"in\" />\n"
" <arg type=\"i\" direction=\"out\" />\n"
" </method>\n"
" <signal name=\"TrackListChange\">\n"
" <arg type=\"i\" />\n"
" </signal>\n"
" </interface>\n"
"</node>\n"
;
// -------------------------------------------------------------------------------- //
guMPRIS::guMPRIS( guDBusServer * server, guPlayerPanel * playerpanel ) : guDBusClient( server )
{
m_PlayerPanel = playerpanel;
RegisterClient();
RequestName( GUAYADEQUE_MPRIS_SERVICENAME );
}
// -------------------------------------------------------------------------------- //
guMPRIS::~guMPRIS()
{
}
// -------------------------------------------------------------------------------- //
void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const char * value )
{
DBusMessageIter dict_entry, variant;
if( value )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_STRING_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_STRING, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const int value )
{
DBusMessageIter dict_entry, variant;
if( value )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_INT32_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_INT32, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
void FillMetadataArgs( guDBusMessage * reply, const guTrack * CurTrack )
{
DBusMessageIter dict;
DBusMessageIter args;
wxASSERT( CurTrack );
const char * metadata_names[] = {
"location", "title", "artist", "album", "tracknumber",
"time", "mtime", "genre", "rating", "year", "arturl", "bitrate"
};
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
FillMetadataDetails( &dict, metadata_names[ 0 ], ( const char * ) ( wxT( "file://" ) + CurTrack->m_FileName ).mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 1 ], ( const char * ) CurTrack->m_SongName.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 2 ], ( const char * ) CurTrack->m_ArtistName.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 3 ], ( const char * ) CurTrack->m_AlbumName.mb_str( wxConvUTF8 ) );
if( CurTrack->m_Number )
FillMetadataDetails( &dict, metadata_names[ 4 ], ( const int ) CurTrack->m_Number );
FillMetadataDetails( &dict, metadata_names[ 5 ], ( const int ) CurTrack->m_Length );
FillMetadataDetails( &dict, metadata_names[ 6 ], ( const int ) CurTrack->m_Length * 1000 );
FillMetadataDetails( &dict, metadata_names[ 7 ], ( const char * ) CurTrack->m_GenreName.mb_str( wxConvUTF8 ) );
if( CurTrack->m_Rating >= 0 )
FillMetadataDetails( &dict, metadata_names[ 8 ], ( const int ) CurTrack->m_Rating );
if( CurTrack->m_Year )
FillMetadataDetails( &dict, metadata_names[ 9 ], ( const int ) CurTrack->m_Year );
//if( !CurTrack->m_CoverPath.IsEmpty() )
// FillMetadataDetails( &dict, metadata_names[ 10 ], ( const char * ) ( wxT( "file://" ) + CurTrack->m_CoverPath ).mb_str( wxConvUTF8 ) );
if( CurTrack->m_Rating )
FillMetadataDetails( &dict, metadata_names[ 11 ], ( const int ) CurTrack->m_Bitrate );
dbus_message_iter_close_container( &args, &dict );
}
// -------------------------------------------------------------------------------- //
void FillMetadataArgs( guDBusMessage * reply, const guCurrentTrack * CurTrack )
{
DBusMessageIter dict;
DBusMessageIter args;
wxASSERT( CurTrack );
const char * metadata_names[] = {
"location", "title", "artist", "album", "tracknumber",
"time", "mtime", "genre", "rating", "year", "arturl", "bitrate"
};
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
FillMetadataDetails( &dict, metadata_names[ 0 ], ( const char * ) ( wxT( "file://" ) + CurTrack->m_FileName ).mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 1 ], ( const char * ) CurTrack->m_SongName.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 2 ], ( const char * ) CurTrack->m_ArtistName.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, metadata_names[ 3 ], ( const char * ) CurTrack->m_AlbumName.mb_str( wxConvUTF8 ) );
if( CurTrack->m_Number )
FillMetadataDetails( &dict, metadata_names[ 4 ], ( const int ) CurTrack->m_Number );
FillMetadataDetails( &dict, metadata_names[ 5 ], ( const int ) CurTrack->m_Length );
FillMetadataDetails( &dict, metadata_names[ 6 ], ( const int ) CurTrack->m_Length * 1000 );
FillMetadataDetails( &dict, metadata_names[ 7 ], ( const char * ) CurTrack->m_GenreName.mb_str( wxConvUTF8 ) );
if( CurTrack->m_Rating >= 0 )
FillMetadataDetails( &dict, metadata_names[ 8 ], ( const int ) CurTrack->m_Rating );
if( CurTrack->m_Year )
FillMetadataDetails( &dict, metadata_names[ 9 ], ( const int ) CurTrack->m_Year );
if( !CurTrack->m_CoverPath.IsEmpty() )
FillMetadataDetails( &dict, metadata_names[ 10 ], ( const char * ) ( wxT( "file://" ) + CurTrack->m_CoverPath ).mb_str( wxConvUTF8 ) );
if( CurTrack->m_Rating )
FillMetadataDetails( &dict, metadata_names[ 11 ], ( const int ) CurTrack->m_Bitrate );
dbus_message_iter_close_container( &args, &dict );
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guMPRIS::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
//
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
const char * Interface = msg->GetInterface();
const char * Member = msg->GetMember();
// const char * Dest = msg->GetDestination();
int Type = msg->GetType();
const char * Path = msg->GetPath();
// int Serial = msg->GetSerial();
// int RSerial = msg->GetReplySerial();
// // Show the details of the msg
// guLogMessage( wxT( "==MPRIS========================" ) );
// guLogMessage( wxT( "Type : %i" ), Type );
// guLogMessage( wxT( "Iface : %s" ), wxString::FromAscii( Interface ).c_str() );
// guLogMessage( wxT( "Dest : %s" ), wxString::FromAscii( Dest ).c_str() );
// guLogMessage( wxT( "Path : %s" ), wxString::FromAscii( Path ).c_str() );
// guLogMessage( wxT( "OPath : %s" ), wxString::FromAscii( msg->GetObjectPath() ).c_str() );
// guLogMessage( wxT( "Member : %s" ), wxString::FromAscii( Member ).c_str() );
// guLogMessage( wxT( "Serial : %i" ), Serial );
// guLogMessage( wxT( "RSerial: %i" ), RSerial );
// If its a method call
if( Type == DBUS_MESSAGE_TYPE_METHOD_CALL )
{
// Some buggie applications send incomplete message calls
if( !Interface || !Member || !Path )
return RetVal;
// INTROSPECT
if( !strcmp( Interface, "org.freedesktop.DBus.Introspectable" ) &&
!strcmp( Member, "Introspect" ) )
{
const char * Dest = msg->GetDestination();
if( Dest && !strcmp( Dest, GUAYADEQUE_MPRIS_SERVICENAME ) )
{
if( !strcmp( Path, "/" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Introspection_XML_Data_Root ) )
{
guLogError( wxT( "Failed to attach the Introspection info" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Path, "/Player" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Introspection_XML_Data_Player ) )
{
guLogError( wxT( "Failed to attach the Introspection info" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Path, "/TrackList" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Introspection_XML_Data_Tracklist ) )
{
guLogError( wxT( "Failed to attach the Introspection info" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( Interface, "org.freedesktop.MediaPlayer" ) )
{
//
// ROOT
//
if( !strcmp( Path, "/" ) )
{
if( !strcmp( Member, "Identity" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
const char * VersionStr = "Guayadeque " ID_GUAYADEQUE_VERSION;
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &VersionStr ) )
{
guLogError( wxT( "Failed to attach the root identity" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Quit" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_MENU_QUIT );
wxPostEvent( m_PlayerPanel, event );
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "MprisVersion" ) )
{
dbus_uint16_t ver_major = GUAYADEQUE_MPRIS_VERSION_MAJOR;
dbus_uint16_t ver_minor = GUAYADEQUE_MPRIS_VERSION_MINOR;
DBusMessageIter verstruct;
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_STRUCT, NULL, &verstruct );
dbus_message_iter_append_basic( &verstruct, DBUS_TYPE_UINT16, &ver_major );
dbus_message_iter_append_basic( &verstruct, DBUS_TYPE_UINT16, &ver_minor );
dbus_message_iter_close_container( &args, &verstruct );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
//
// PLAYER
//
else if( !strcmp( Path, "/Player" ) )
{
if( !strcmp( Member, "Next" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_NEXTTRACK );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Prev" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PREVTRACK );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "NextAlbum" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_NEXTALBUM );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "PrevAlbum" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PREVALBUM );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Pause" ) )
{
//if( m_PlayerPanel->GetState() == guMediaState_PLAYING )
//{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
//}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Stop" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_STOP );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Play" ) )
{
// if( m_PlayerPanel->GetState() <= guMEDIASTATE_PAUSED )
// {
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
// }
// else
// {
// wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_STOP );
// wxPostEvent( m_PlayerPanel, event );
// event.SetId( ID_PLAYERPANEL_PLAY );
// wxPostEvent( m_PlayerPanel, event );
// }
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Repeat" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETREPEAT );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "GetStatus" ) )
{
int PlayStatus;
int Dummy = 0;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlayStatus = 2;
else if( State == guMEDIASTATE_PAUSED )
PlayStatus = 1;
else if( State == guMEDIASTATE_PLAYING )
PlayStatus = 0;
int PlaySingle = ( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_TRACK );
int PlayLoop = ( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
DBusMessageIter status;
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_STRUCT, NULL, &status );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlayStatus );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &Dummy );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlaySingle );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlayLoop );
dbus_message_iter_close_container( &args, &status );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "GetMetadata" ) )
{
const guCurrentTrack * CurTrack = m_PlayerPanel->GetCurrentTrack();
if( CurTrack )
{
FillMetadataArgs( reply, CurTrack );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "GetCaps" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
int Caps = m_PlayerPanel->GetCaps();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &Caps ) )
{
guLogError( wxT( "Failed to attach the player Caps" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "VolumeSet" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_int32_t Volume;
dbus_message_get_args( msg->GetMessage(), &error, DBUS_TYPE_INT32, &Volume, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the Volume parameter : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETVOLUME );
event.SetInt( Volume );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "VolumeGet" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
int Volume = m_PlayerPanel->GetVolume();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &Volume ) )
{
guLogError( wxT( "Failed to attach the Player volume" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "PositionSet" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_int32_t Position;
dbus_message_get_args( msg->GetMessage(), &error, DBUS_TYPE_INT32, &Position, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the Position parameter : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
m_PlayerPanel->SetPosition( Position );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "PositionGet" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
int Position = m_PlayerPanel->GetPosition();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &Position ) )
{
guLogError( wxT( "Failed to attach the Player position" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
//
// TRACKLIST
//
else if( !strcmp( Path, "/TrackList" ) )
{
if( !strcmp( Member, "GetMetadata" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_int32_t TrackNum;
dbus_message_get_args( msg->GetMessage(), &error, DBUS_TYPE_INT32, &TrackNum, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not get the GetMetadata parameter : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
const guTrack * CurTrack = m_PlayerPanel->GetTrack( TrackNum );
if( CurTrack )
{
FillMetadataArgs( reply, CurTrack );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "GetCurrentTrack" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
int CurTrack = m_PlayerPanel->GetCurrentItem();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &CurTrack ) )
{
guLogError( wxT( "Failed to attach the Player position" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "GetLength" ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
int TrackCnt = m_PlayerPanel->GetItemCount();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &TrackCnt ) )
{
guLogError( wxT( "Failed to attach the Player position" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "AddTrack" ) )
{
DBusError error;
dbus_error_init( &error );
const char * TrackPath;
dbus_bool_t PlayTrack;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_STRING, &TrackPath,
DBUS_TYPE_BOOLEAN, &PlayTrack,
DBUS_TYPE_INVALID );
//guLogMessage( wxT( "MPRIS: AddTrack\n%s\n%i" ), wxString( TrackPath, wxConvUTF8 ).c_str(), PlayTrack );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the AddTrack parameters : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
wxArrayString * TrackList = new wxArrayString();
TrackList->Add( wxString( TrackPath, wxConvUTF8 ) );
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_ADDTRACKS );
event.SetInt( PlayTrack );
event.SetClientData( TrackList );
wxPostEvent( m_PlayerPanel, event );
int TrackAdded = 1;
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &TrackAdded ) )
{
guLogError( wxT( "Failed to attach the AddTrack return code" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "AddTracks" ) )
{
DBusError error;
dbus_error_init( &error );
char ** Tracks;
dbus_int32_t TracksCount;
dbus_bool_t PlayTrack;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &Tracks, &TracksCount,
DBUS_TYPE_BOOLEAN, &PlayTrack,
DBUS_TYPE_INVALID );
//
// //guLogMessage( wxT( "MPRIS: AddTrack\n%s\n%i" ), wxString( TrackPath, wxConvUTF8 ).c_str(), PlayTrack );
//
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the AddTracks parameters : '%s'" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
wxArrayString * TrackList = new wxArrayString();
for( int Index = 0; Index < TracksCount; Index++ )
{
TrackList->Add( wxString( Tracks[ Index ], wxConvUTF8 ) );
}
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_ADDTRACKS );
event.SetInt( PlayTrack );
event.SetClientData( TrackList );
wxPostEvent( m_PlayerPanel, event );
int TrackAdded = 1;
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &TrackAdded ) )
{
guLogError( wxT( "Failed to attach the AddTrack return code" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "DelTrack" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_int32_t TrackNum;
dbus_message_get_args( msg->GetMessage(), &error, DBUS_TYPE_INT32, &TrackNum, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not get DelTrack parameter : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_REMOVETRACK );
event.SetInt( TrackNum );
wxPostEvent( m_PlayerPanel, event );
//Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "SetLoop" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_bool_t PlayLoop;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_BOOLEAN, &PlayLoop,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the AddTrack parameters : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETLOOP );
event.SetInt( PlayLoop );
wxPostEvent( m_PlayerPanel, event );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "SetRandom" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_bool_t Random;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_BOOLEAN, &Random,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the AddTrack parameters : %s\n", error.message );
dbus_error_free( &error );
RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETRANDOM );
wxPostEvent( m_PlayerPanel, event );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guMPRIS::OnPlayerTrackChange()
{
guDBusSignal * signal = new guDBusSignal( "/Player", "org.freedesktop.MediaPlayer", "TrackChange" );
if( signal )
{
const guCurrentTrack * CurTrack = m_PlayerPanel->GetCurrentTrack();
FillMetadataArgs( signal, CurTrack );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create CapsChange signal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS::OnPlayerStatusChange()
{
guDBusSignal * signal = new guDBusSignal( "/Player", "org.freedesktop.MediaPlayer", "StatusChange" );
if( signal )
{
int PlayStatus;
int Dummy = 0;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlayStatus = 2;
else if( State == guMEDIASTATE_PAUSED )
PlayStatus = 1;
else if( State == guMEDIASTATE_PLAYING )
PlayStatus = 0;
int PlaySingle = ( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_TRACK );
int PlayLoop = ( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
guLogMessage( wxT( "StatusChanged( %i, %i, %i, %i )" ), PlayStatus, Dummy, Dummy, PlayLoop );
DBusMessageIter status;
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_STRUCT, NULL, &status );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlayStatus );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &Dummy );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlaySingle );
dbus_message_iter_append_basic( &status, DBUS_TYPE_INT32, &PlayLoop );
dbus_message_iter_close_container( &args, &status );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create CapsChange signal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS::OnPlayerCapsChange()
{
guDBusSignal * signal = new guDBusSignal( "/Player", "org.freedesktop.MediaPlayer", "CapsChange" );
if( signal )
{
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
int Caps = m_PlayerPanel->GetCaps();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &Caps ) )
{
guLogError( wxT( "Failed to attach the player Caps" ) );
}
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create CapsChange signal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS::OnTrackListChange()
{
guDBusSignal * signal = new guDBusSignal( "/TrackList", "org.freedesktop.MediaPlayer", "TrackListChange" );
if( signal )
{
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
int TrackCnt = m_PlayerPanel->GetItemCount();
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_INT32, &TrackCnt ) )
{
guLogError( wxT( "Failed to attach the TrackCount" ) );
}
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create TrackListChange signal object" ) );
}
}
}
// -------------------------------------------------------------------------------- //
| 40,354
|
C++
|
.cpp
| 876
| 32.710046
| 145
| 0.484123
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,557
|
mpris2.cpp
|
anonbeat_guayadeque/src/dbus/mpris2.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "mpris2.h"
#include "EventCommandIds.h"
#include "GstTypeFinder.h"
#include "mpris.h"
#include "Utils.h"
#include "MainFrame.h"
namespace Guayadeque {
// See http://www.mpris.org/2.0/spec/index.html
#define GUAYADEQUE_MPRIS2_SERVICE_NAME "org.mpris.MediaPlayer2.guayadeque"
#define GUAYADEQUE_MPRIS2_OBJECT_PATH "/org/mpris/MediaPlayer2"
#define GUAYADEQUE_MPRIS2_PLAYER_PATH "/org/mpris/MediaPlayer2/Player"
#define GUAYADEQUE_PROPERTIES_INTERFACE "org.freedesktop.DBus.Properties"
#define GUAYADEQUE_MPRIS2_INTERFACE_ROOT "org.mpris.MediaPlayer2"
#define GUAYADEQUE_MPRIS2_INTERFACE_PLAYER "org.mpris.MediaPlayer2.Player"
#define GUAYADEQUE_MPRIS2_INTERFACE_TRACKLIST "org.mpris.MediaPlayer2.TrackList"
#define GUAYADEQUE_MPRIS2_INTERFACE_PLAYLISTS "org.mpris.MediaPlayer2.Playlists"
const char * GUAYADEQUE_SUPPORTED_MIME_TYPES[] = {
"application/ogg",
"application/x-ogg",
"application/x-ogm-audio",
"audio/aac",
"audio/ape",
"audio/mp4",
"audio/mpc",
"audio/mpeg",
"audio/mpegurl",
"audio/ogg",
"audio/vnd.rn-realaudio",
"audio/vorbis",
"audio/x-flac",
"audio/x-mp3",
"audio/x-mpeg",
"audio/x-mpegurl",
"audio/x-ms-wma",
"audio/x-musepack",
"audio/x-oggflac",
"audio/x-pn-realaudio",
"audio/x-scpls",
"audio/x-speex",
"audio/x-vorbis",
"audio/x-vorbis+ogg",
"audio/x-wav",
"video/x-ms-asf",
"x-content/audio-player",
NULL };
const char * guMPRIS2_INTROSPECTION_XML =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
"<node>\n"
" <interface name='org.mpris.MediaPlayer2'>\n"
" <method name='Raise'/>\n"
" <method name='Quit'/>\n"
" <property name='CanQuit' type='b' access='read'/>\n"
" <property name='Fullscreen' type='b' access='readwrite'/>\n"
" <property name='CanSetFullscreen' type='b' access='read'/>\n"
" <property name='CanRaise' type='b' access='read'/>\n"
" <property name='HasTrackList' type='b' access='read'/>\n"
" <property name='Identity' type='s' access='read'/>\n"
" <property name='DesktopEntry' type='s' access='read'/>\n"
" <property name='SupportedUriSchemes' type='as' access='read'/>\n"
" <property name='SupportedMimeTypes' type='as' access='read'/>\n"
" </interface>\n"
" <interface name='org.mpris.MediaPlayer2.Player'>\n"
" <method name='Next'/>\n"
" <method name='NextAlbum'/>\n" // Non-standard
" <method name='Previous'/>\n"
" <method name='PreviousAlbum'/>\n" // Non-standard
" <method name='Pause'/>\n"
" <method name='PlayPause'/>\n"
" <method name='Stop'/>\n"
" <method name='Play'/>\n"
" <method name='Seek'>\n"
" <arg direction='in' name='Offset' type='x'/>\n"
" </method>\n"
" <method name='SetPosition'>\n"
" <arg direction='in' name='TrackId' type='o'/>\n"
" <arg direction='in' name='Position' type='x'/>\n"
" </method>\n"
" <method name='OpenUri'>\n"
" <arg direction='in' name='Uri' type='s'/>\n"
" </method>\n"
" <signal name='Seeked'>\n"
" <arg name='Position' type='x'/>\n"
" </signal>\n"
" <property name='PlaybackStatus' type='s' access='read'/>\n"
" <property name='LoopStatus' type='s' access='readwrite'/>\n"
" <property name='Rate' type='d' access='readwrite'/>\n"
" <property name='Shuffle' type='b' access='readwrite'/>\n"
" <property name='Metadata' type='a{sv}' access='read'/>\n"
" <property name='Volume' type='d' access='readwrite'/>\n"
" <property name='Position' type='x' access='read'/>\n"
" <property name='MinimumRate' type='d' access='read'/>\n"
" <property name='MaximumRate' type='d' access='read'/>\n"
" <property name='CanGoNext' type='b' access='read'/>\n"
" <property name='CanGoPrevious' type='b' access='read'/>\n"
" <property name='CanPlay' type='b' access='read'/>\n"
" <property name='CanPause' type='b' access='read'/>\n"
" <property name='CanSeek' type='b' access='read'/>\n"
" <property name='CanControl' type='b' access='read'/>\n"
" </interface>\n"
" <interface name='org.mpris.MediaPlayer2.TrackList'>\n"
" <method name='GetTracksMetadata'>\n"
" <arg direction='in' name='TrackIds' type='ao'/>\n"
" <arg direction='out' name='Metadata' type='aa{sv}'/>\n"
" </method>\n"
" <method name='AddTrack'>\n"
" <arg direction='in' name='Uri' type='s'/>\n"
" <arg direction='in' name='AfterTrack' type='o'/>\n"
" <arg direction='in' name='SetAsCurrent' type='b'/>\n"
" </method>\n"
" <method name='RemoveTrack'>\n"
" <arg direction='in' name='TrackId' type='o'/>\n"
" </method>\n"
" <method name='GoTo'>\n"
" <arg direction='in' name='TrackId' type='o'/>\n"
" </method>\n"
" <signal name='TrackListReplaced'>\n"
" <arg name='Tracks' type='ao'/>\n"
" <arg name='CurrentTrack' type='o'/>\n"
" </signal>\n"
" <signal name='TrackAdded'>\n"
" <arg name='Metadata' type='a{sv}'/>\n"
" <arg name='AfterTrack' type='o'/>\n"
" </signal>\n"
" <signal name='TrackRemoved'>\n"
" <arg name='TrackId' type='o'/>\n"
" </signal>\n"
" <signal name='TrackMetadataChanged'>\n"
" <arg name='TrackId' type='o'/>\n"
" <arg name='Metadata' type='a{sv}'/>\n"
" </signal>\n"
" <property name='Tracks' type='ao' access='read'/>\n"
" <property name='CanEditTracks' type='b' access='read'/>\n"
" </interface>\n"
" <interface name='org.mpris.MediaPlayer2.Playlists'>\n"
" <method name='ActivatePlaylist'>\n"
" <arg direction='in' name='PlaylistId' type='o'/>\n"
" </method>\n"
" <method name='GetPlaylists'>\n"
" <arg direction='in' name='Index' type='u'/>\n"
" <arg direction='in' name='MaxCount' type='u'/>\n"
" <arg direction='in' name='Order' type='s'/>\n"
" <arg direction='in' name='ReverseOrder' type='b'/>\n"
" <arg direction='out' name='Playlists' type='a(oss)'/>\n"
" </method>\n"
" <signal name='PlaylistChanged'>\n"
" <arg name='Playlist' type='b(oss)'/>\n"
" </signal>\n"
" <property name='PlaylistCount' type='u' access='read'/>\n"
" <property name='Orderings' type='as' access='read'/>\n"
" <property name='ActivePlaylist' type='b(oss)' access='read'/>\n"
" </interface>\n"
"</node>\n";
guMPRIS2 * guMPRIS2::m_MPRIS2 = NULL;
char ** GUAYADEQUE_SUPPORTED_MIME_TYPES_WITH_GST = NULL;
// -------------------------------------------------------------------------------- //
const char ** guMPRIS2::GetSupportedMimeTypes( void )
{
if( GUAYADEQUE_SUPPORTED_MIME_TYPES_WITH_GST != NULL )
return (const char**)GUAYADEQUE_SUPPORTED_MIME_TYPES_WITH_GST;
if( !guGstTypeFinder::getGTF().HasPrefixes() )
return GUAYADEQUE_SUPPORTED_MIME_TYPES;
static wxMutex mf_mutex;
mf_mutex.Lock();
int gsmt_count = 0;
while( GUAYADEQUE_SUPPORTED_MIME_TYPES[gsmt_count] != NULL )
gsmt_count++;
wxArrayString arr = guGstTypeFinder::getGTF().GetMediaTypes();
long unsigned int mime_ptr_size =
sizeof(char*) * arr.Count() +
sizeof(char*) * gsmt_count +
sizeof(char*);
char ** all_media = (char **) malloc( mime_ptr_size );
for( size_t i = 0; i < arr.Count(); ++i )
{
const char * mbstr = arr[i].mb_str();
all_media[i] = strdup(mbstr);
}
for( int i = 0; i < gsmt_count; ++i )
{
const char * etstr = GUAYADEQUE_SUPPORTED_MIME_TYPES[i];
all_media[ arr.Count() + i ] = strdup( etstr );
}
all_media[arr.Count() + gsmt_count] = NULL;
GUAYADEQUE_SUPPORTED_MIME_TYPES_WITH_GST = all_media;
mf_mutex.Unlock();
return (const char**)all_media;
}
// -------------------------------------------------------------------------------- //
guMPRIS2::guMPRIS2( guDBusServer * server, guPlayerPanel * playerpanel, guDbLibrary * db ) : guDBusClient( server )
{
m_PlayerPanel = playerpanel;
m_Db = db;
RegisterClient();
RequestName( GUAYADEQUE_MPRIS2_SERVICE_NAME );
RegisterObjectPath( GUAYADEQUE_MPRIS2_OBJECT_PATH );
}
// -------------------------------------------------------------------------------- //
guMPRIS2::~guMPRIS2()
{
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const char * value )
{
DBusMessageIter dict_entry, variant;
if( value )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_STRING_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_STRING, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const char ** value )
{
const char **Str;
DBusMessageIter dict_entry, variant, array;
if( value )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, "as", &variant );
dbus_message_iter_open_container( &variant, DBUS_TYPE_ARRAY, "s", &array );
for( Str = value; * Str; Str++ )
dbus_message_iter_append_basic( &array, DBUS_TYPE_STRING, Str );
dbus_message_iter_close_container( &variant, &array );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const int value )
{
DBusMessageIter dict_entry, variant;
if( name )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_INT32_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_INT32, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const gint64 value )
{
DBusMessageIter dict_entry, variant;
if( name )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_INT64_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_INT64, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const double value )
{
DBusMessageIter dict_entry, variant;
if( name )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_DOUBLE_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_DOUBLE, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const dbus_bool_t value )
{
DBusMessageIter dict_entry, variant;
if( name )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, DBUS_TYPE_BOOLEAN_AS_STRING, &variant );
dbus_message_iter_append_basic( &variant, DBUS_TYPE_BOOLEAN, &value );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const dbus_bool_t plstate,
const char * plpath, const char * plname, const char * plicon )
{
DBusMessageIter dict_entry, vstruct, ostruct, plstruct;
if( name )
{
guLogMessage( wxT( "playlist active %i" ), plstate );
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, "(b(oss))", &vstruct );
dbus_message_iter_open_container( &vstruct, DBUS_TYPE_STRUCT, NULL, &ostruct );
dbus_message_iter_append_basic( &ostruct, DBUS_TYPE_BOOLEAN, &plstate );
dbus_message_iter_open_container( &ostruct, DBUS_TYPE_STRUCT, NULL, &plstruct );
dbus_message_iter_append_basic( &plstruct, DBUS_TYPE_OBJECT_PATH, &plpath );
dbus_message_iter_append_basic( &plstruct, DBUS_TYPE_STRING, &plname );
dbus_message_iter_append_basic( &plstruct, DBUS_TYPE_STRING, &plicon );
dbus_message_iter_close_container( &ostruct, &plstruct );
dbus_message_iter_close_container( &vstruct, &ostruct );
dbus_message_iter_close_container( &dict_entry, &vstruct );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataAsList( DBusMessageIter * Iter, const char * name, const char * value )
{
DBusMessageIter dict_entry, variant, array;
if( value && strlen( value ) )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, "as", &variant );
dbus_message_iter_open_container( &variant, DBUS_TYPE_ARRAY, "s", &array );
dbus_message_iter_append_basic( &array, DBUS_TYPE_STRING, &value );
dbus_message_iter_close_container( &variant, &array );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataIter( DBusMessageIter * iter, const guCurrentTrack * curtrack, const int trackid )
{
DBusMessageIter dict;
dbus_message_iter_open_container( iter, DBUS_TYPE_ARRAY, "{sv}", &dict );
FillMetadataDetails( &dict, "mpris:trackid", ( const char * ) wxString::Format( wxT( "/org/mpris/MediaPlayer2/Track/%u" ), trackid ).mb_str( wxConvUTF8 ) );
if( curtrack && curtrack->m_Loaded )
{
wxString LocationUrl = wxT( "file://" ) + curtrack->m_FileName;
LocationUrl.Replace( wxT( " "), wxT( "%20" ) );
FillMetadataDetails( &dict, "xesam:url", ( const char * ) LocationUrl.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, "xesam:title", ( const char * ) curtrack->m_SongName.mb_str( wxConvUTF8 ) );
FillMetadataAsList( &dict, "xesam:artist", ( const char * ) curtrack->m_ArtistName.mb_str( wxConvUTF8 ) );
FillMetadataAsList( &dict, "xesam:albumArtist", ( const char * ) curtrack->m_AlbumArtist.mb_str( wxConvUTF8 ) );
FillMetadataAsList( &dict, "xesam:comment", ( const char * ) curtrack->m_Comments.mb_str( wxConvUTF8 ) );
FillMetadataAsList( &dict, "xesam:composer", ( const char * ) curtrack->m_Composer.mb_str( wxConvUTF8 ) );
FillMetadataDetails( &dict, "xesam:album", ( const char * ) curtrack->m_AlbumName.mb_str( wxConvUTF8 ) );
if( curtrack->m_Number )
FillMetadataDetails( &dict, "xesam:trackNumber", ( const int ) curtrack->m_Number );
FillMetadataDetails( &dict, "mpris:length", ( const gint64 ) gint64( curtrack->m_Length * 1000 ) );
FillMetadataAsList( &dict, "xesan:genre", ( const char * ) curtrack->m_GenreName.mb_str( wxConvUTF8 ) );
if( curtrack->m_Rating >= 0 )
FillMetadataDetails( &dict, "xesam:userRating", ( const double ) double( curtrack->m_Rating * 0.2 ) );
if( curtrack->m_Year )
{
FillMetadataDetails( &dict, "xesam:contentCreated", ( const char * ) wxString::Format( wxT( "%4d-%02d-%02dT%02d:%02d:%02dZ" ), curtrack->m_Year, 1, 1, 0, 0, 0 ).mb_str( wxConvUTF8 ) );
}
FillMetadataDetails( &dict, "xesam:useCount", ( const int ) curtrack->m_PlayCount );
if( curtrack->m_CoverType == GU_SONGCOVER_ID3TAG )
{
wxString TempFile = wxFileName::GetTempDir() + wxT( "/" ) + guTEMPORARY_COVER_FILENAME + wxT( "1.png" );
if( !wxFileExists( TempFile ) )
{
TempFile.RemoveLast( 5 );
TempFile.Append( wxT( "2.png" ) );
}
if( wxFileExists( TempFile ) )
FillMetadataDetails( &dict, "mpris:artUrl", ( const char * ) ( wxT( "file://" ) + TempFile ).mb_str( wxConvUTF8 ) );
}
else if( !curtrack->m_CoverPath.IsEmpty() )
{
FillMetadataDetails( &dict, "mpris:artUrl", ( const char * ) ( wxT( "file://" ) + curtrack->m_CoverPath ).mb_str( wxConvUTF8 ) );
}
if( curtrack->m_Bitrate )
FillMetadataDetails( &dict, "xesam:audioBitrate", ( const int ) curtrack->m_Bitrate * 1000 );
}
dbus_message_iter_close_container( iter, &dict );
}
// -------------------------------------------------------------------------------- //
static void FillMetadataDetails( DBusMessageIter * Iter, const char * name, const guCurrentTrack * curtrack, const int trackid )
{
DBusMessageIter dict_entry, variant;
if( name && strlen( name ) )
{
dbus_message_iter_open_container( Iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &name );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, "a{sv}", &variant );
FillMetadataIter( &variant, curtrack, trackid );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( Iter, &dict_entry );
}
}
// -------------------------------------------------------------------------------- //
static void FillMetadataArgs( guDBusMessage * reply, const guCurrentTrack * curtrack, const int trackid )
{
DBusMessageIter args, variant;
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_VARIANT, "a{sv}", &variant );
FillMetadataIter( &variant, curtrack, trackid );
dbus_message_iter_close_container( &args, &variant );
}
// -------------------------------------------------------------------------------- //
static bool AddVariant( DBusMessage * msg, const int type, const void * data )
{
DBusMessageIter iter, sub;
char Types[ 2 ];
Types[ 0 ] = ( char ) type;
Types[ 1 ] = DBUS_TYPE_INVALID;
dbus_message_iter_init_append( msg, &iter );
return dbus_message_iter_open_container( &iter, DBUS_TYPE_VARIANT, Types, &sub ) &&
dbus_message_iter_append_basic( &sub, type, data ) &&
dbus_message_iter_close_container( &iter, &sub );
}
// -------------------------------------------------------------------------------- //
static bool GetVariant( DBusMessage * msg, const int type, void * data )
{
DBusMessageIter iter, variant;
if( !dbus_message_iter_init( msg, &iter ) )
{
guLogMessage( wxT( "GetVariant called without arguments" ) );
return false;
}
do {
if( dbus_message_iter_get_arg_type( &iter ) == DBUS_TYPE_VARIANT )
{
guLogMessage( wxT( "Found the Variant variable") );
dbus_message_iter_recurse( &iter, &variant );
if( dbus_message_iter_get_arg_type( &variant ) == type )
{
dbus_message_iter_get_basic( &variant, data );
return true;
}
}
} while( dbus_message_iter_next( &iter ) );
return false;
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnPlayerTrackChange( void )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_PROPERTIES_INTERFACE, "PropertiesChanged" );
if( signal )
{
DBusMessageIter args;
DBusMessageIter dict;
dbus_message_iter_init_append( signal->GetMessage(), &args );
const char * Interface = GUAYADEQUE_MPRIS2_INTERFACE_PLAYER;
dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Interface );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
DBusMessageIter dict_entry, variant;
dbus_message_iter_open_container( &dict, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry );
const char * Metadata = "Metadata";
dbus_message_iter_append_basic( &dict_entry, DBUS_TYPE_STRING, &Metadata );
dbus_message_iter_open_container( &dict_entry, DBUS_TYPE_VARIANT, "a{sv}", &variant );
const guCurrentTrack * CurTrack = m_PlayerPanel->GetCurrentTrack();
const int TrackId = m_PlayerPanel->GetCurrentItem();
FillMetadataIter( &variant, CurTrack, TrackId );
dbus_message_iter_close_container( &dict_entry, &variant );
dbus_message_iter_close_container( &dict, &dict_entry );
const char * PlaybackStatus;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlaybackStatus = "Stopped";
else if( State == guMEDIASTATE_PAUSED )
PlaybackStatus = "Paused";
else //if( State == guMEDIASTATE_PLAYING )
PlaybackStatus = "Playing";
FillMetadataDetails( &dict, "PlaybackStatus", PlaybackStatus );
const char * LoopStatus;
int PlayLoop = m_PlayerPanel->GetPlayMode();
if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_TRACK )
LoopStatus = "Track";
else if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_PLAYLIST )
LoopStatus = "Playlist";
else //if( PlayLoop == guPLAYER_PLAYMODE_NONE )
LoopStatus = "None";
FillMetadataDetails( &dict, "LoopStatus", LoopStatus );
int Caps = m_PlayerPanel->GetCaps();
dbus_bool_t CanGoNext = ( Caps & MPRIS_CAPS_CAN_GO_NEXT ) > 0;
FillMetadataDetails( &dict, "CanGoNext", CanGoNext );
dbus_bool_t CanGoPrev = ( Caps & MPRIS_CAPS_CAN_GO_PREV ) > 0;
FillMetadataDetails( &dict, "CanGoPrevious", CanGoPrev );
dbus_bool_t CanPlay = ( Caps & MPRIS_CAPS_CAN_PLAY ) > 0;
FillMetadataDetails( &dict, "CanPlay", CanPlay );
dbus_bool_t CanPause = ( Caps & MPRIS_CAPS_CAN_PAUSE ) > 0;
FillMetadataDetails( &dict, "CanPause", CanPause );
dbus_bool_t CanSeek = ( Caps & MPRIS_CAPS_CAN_SEEK ) > 0;
FillMetadataDetails( &dict, "CanSeek", CanSeek );
dbus_message_iter_close_container( &args, &dict );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "s", &dict );
dbus_message_iter_close_container( &args, &dict );
//const char * Signature = dbus_message_get_signature( signal->GetMessage() );
//guLogMessage( wxT( "Signal signature: '%s'" ), wxString( Signature, wxConvUTF8 ).c_str() );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create EmitPropertyChangedSignal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnPlayerStatusChange( void )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_PROPERTIES_INTERFACE, "PropertiesChanged" );
if( signal )
{
DBusMessageIter dict;
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
const char * Interface = GUAYADEQUE_MPRIS2_INTERFACE_PLAYER;
dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Interface );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
const char * PlaybackStatus;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlaybackStatus = "Stopped";
else if( State == guMEDIASTATE_PAUSED )
PlaybackStatus = "Paused";
else //if( State == guMEDIASTATE_PLAYING )
PlaybackStatus = "Playing";
FillMetadataDetails( &dict, "PlaybackStatus", PlaybackStatus );
const char * LoopStatus;
int PlayLoop = m_PlayerPanel->GetPlayMode();
if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_TRACK )
LoopStatus = "Track";
else if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_PLAYLIST )
LoopStatus = "Playlist";
else //if( PlayLoop == guPLAYER_PLAYMODE_NONE )
LoopStatus = "None";
FillMetadataDetails( &dict, "LoopStatus", LoopStatus );
dbus_message_iter_close_container( &args, &dict );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "s", &dict );
dbus_message_iter_close_container( &args, &dict );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create EmitPropertyChangedSignal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnPlayerCapsChange( void )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_PROPERTIES_INTERFACE, "PropertiesChanged" );
if( signal )
{
DBusMessageIter dict;
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
const char * Interface = GUAYADEQUE_MPRIS2_INTERFACE_PLAYER;
dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Interface );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
int Caps = m_PlayerPanel->GetCaps();
dbus_bool_t CanGoNext = ( Caps & MPRIS_CAPS_CAN_GO_NEXT ) > 0;
FillMetadataDetails( &dict, "CanGoNext", CanGoNext );
dbus_bool_t CanGoPrev = ( Caps & MPRIS_CAPS_CAN_GO_PREV ) > 0;
FillMetadataDetails( &dict, "CanGoPrevious", CanGoPrev );
dbus_bool_t CanPlay = ( Caps & MPRIS_CAPS_CAN_PLAY ) > 0;
FillMetadataDetails( &dict, "CanPlay", CanPlay );
dbus_bool_t CanPause = ( Caps & MPRIS_CAPS_CAN_PAUSE ) > 0;
FillMetadataDetails( &dict, "CanPause", CanPause );
dbus_message_iter_close_container( &args, &dict );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "s", &dict );
dbus_message_iter_close_container( &args, &dict );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create EmitPropertyChangedSignal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnPlayerVolumeChange( void )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_PROPERTIES_INTERFACE, "PropertiesChanged" );
if( signal )
{
DBusMessageIter dict;
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
const char * Interface = GUAYADEQUE_MPRIS2_INTERFACE_PLAYER;
dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Interface );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
double CurVolume = m_PlayerPanel->GetVolume() / 100;
FillMetadataDetails( &dict, "Volume", CurVolume );
dbus_message_iter_close_container( &args, &dict );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "s", &dict );
dbus_message_iter_close_container( &args, &dict );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create EmitPropertyChangedSignal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnPlayerSeeked( const unsigned int newpos )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_MPRIS2_INTERFACE_PLAYER, "Seeked" );
if( signal )
{
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
gint64 Position = newpos * 1000;
dbus_message_iter_append_basic( &args, DBUS_TYPE_INT64, &Position );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create Seeked signal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnTrackListChange( void )
{
}
// -------------------------------------------------------------------------------- //
void guMPRIS2::OnFullscreenChanged( void )
{
guDBusSignal * signal = new guDBusSignal( GUAYADEQUE_MPRIS2_OBJECT_PATH, GUAYADEQUE_PROPERTIES_INTERFACE, "PropertiesChanged" );
if( signal )
{
DBusMessageIter dict;
DBusMessageIter args;
dbus_message_iter_init_append( signal->GetMessage(), &args );
const char * Interface = GUAYADEQUE_MPRIS2_INTERFACE_ROOT;
dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &Interface );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
guMainFrame * MainFrame = guMainFrame::GetMainFrame();
dbus_bool_t FullScreen = MainFrame->IsFullScreen();
FillMetadataDetails( &dict, "Fullscreen", FullScreen );
dbus_message_iter_close_container( &args, &dict );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "s", &dict );
dbus_message_iter_close_container( &args, &dict );
Send( signal );
Flush();
delete signal;
}
else
{
guLogError( wxT( "Could not create EmitPropertyChangedSignal object" ) );
}
}
// -------------------------------------------------------------------------------- //
void inline IterAppendBasic( DBusMessageIter * iter, const int type, const char * value )
{
dbus_message_iter_append_basic( iter, type, &value );
}
// -------------------------------------------------------------------------------- //
void AppendPlaylist( DBusMessageIter * iter, guListItem &playlist )
{
DBusMessageIter plstruct;
const char * plicon = "";
dbus_message_iter_open_container( iter, DBUS_TYPE_STRUCT, NULL, &plstruct );
IterAppendBasic( &plstruct, DBUS_TYPE_OBJECT_PATH,
wxString::Format( wxT( "/org/mpris/MediaPlayer2/guayadeque/Playlist/%i" ), playlist.m_Id ).mb_str( wxConvUTF8 ) );
IterAppendBasic( &plstruct, DBUS_TYPE_STRING, playlist.m_Name.mb_str( wxConvUTF8 ) );
IterAppendBasic( &plstruct, DBUS_TYPE_STRING, plicon );
dbus_message_iter_close_container( iter, &plstruct );
}
// -------------------------------------------------------------------------------- //
bool guMPRIS2::GetPlaylists( DBusMessage * msg, const dbus_int32_t start, const dbus_int32_t maxcount,
const char * order, const dbus_bool_t reverseorder )
{
DBusMessageIter args, arrentry;
guListItems Playlists;
m_Db->GetPlayLists( Playlists );
dbus_message_iter_init_append( msg, &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "(oss)", &arrentry );
int Count = wxMin( start + maxcount, ( int ) Playlists.Count() );
for( int Index = start; Index < Count; Index++ )
{
AppendPlaylist( &arrentry, Playlists[ Index ] );
}
dbus_message_iter_close_container( &args, &arrentry );
return true;
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guMPRIS2::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
//
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
const char * Interface = msg->GetInterface();
const char * Member = msg->GetMember();
int Type = msg->GetType();
const char * Path = msg->GetPath();
// int Serial = msg->GetSerial();
// int RSerial = msg->GetReplySerial();
// Show the details of the msg
// const char * Dest = msg->GetDestination();
// guLogMessage( wxT( "==MPRIS2========================" ) );
// guLogMessage( wxT( "Type : %i" ), Type );
// guLogMessage( wxT( "Iface : %s" ), wxString::FromAscii( Interface ).c_str() );
// guLogMessage( wxT( "Dest : %s" ), wxString::FromAscii( Dest ).c_str() );
// guLogMessage( wxT( "Path : %s" ), wxString::FromAscii( Path ).c_str() );
// guLogMessage( wxT( "OPath : %s" ), wxString::FromAscii( msg->GetObjectPath() ).c_str() );
// guLogMessage( wxT( "Member : %s" ), wxString::FromAscii( Member ).c_str() );
// guLogMessage( wxT( "Serial : %i" ), Serial );
// guLogMessage( wxT( "RSerial: %i" ), RSerial );
// If its a method call
if( Type == DBUS_MESSAGE_TYPE_METHOD_CALL )
{
// Some buggie applications send incomplete message calls
if( !Interface || !Member || !Path )
return RetVal;
if( !strcmp( Interface, "org.freedesktop.DBus.Introspectable" ) )
{
if( !strcmp( Member, "Introspect" ) )
{
const char * Dest = msg->GetDestination();
if( Dest && !strcmp( Dest, GUAYADEQUE_MPRIS2_SERVICE_NAME ) )
{
DBusMessageIter args;
dbus_message_iter_init_append( reply->GetMessage(), &args );
if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &guMPRIS2_INTROSPECTION_XML ) )
{
guLogError( wxT( "Failed to attach the Introspection info" ) );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( Interface, GUAYADEQUE_PROPERTIES_INTERFACE ) )
{
if( !strcmp( Path, "/org/mpris/MediaPlayer2" ) )
{
DBusError error;
dbus_error_init( &error );
if( !strcmp( Member, "GetAll" ) )
{
const char * QueryIface;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_STRING, &QueryIface,
DBUS_TYPE_INVALID );
// guLogMessage( wxT( "QIface : %s" ), wxString::FromAscii( QueryIface ).c_str() );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
DBusMessageIter args;
DBusMessageIter dict;
if( !strcmp( QueryIface, "org.mpris.MediaPlayer2" ) )
{
dbus_bool_t ReplyVal = true;
guMainFrame * MainFrame = guMainFrame::GetMainFrame();
dbus_bool_t FullScreen = MainFrame->IsFullScreen();
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
FillMetadataDetails( &dict, "CanQuit", ReplyVal );
FillMetadataDetails( &dict, "Fullscreen", FullScreen );
FillMetadataDetails( &dict, "CanSetFullscreen", ReplyVal );
FillMetadataDetails( &dict, "CanRaise", ReplyVal );
FillMetadataDetails( &dict, "HasTrackList", ReplyVal );
const char * AppName = "Guayadeque Music Player";
FillMetadataDetails( &dict, "Identity", AppName );
const char * DesktopPath = "guayadeque";
FillMetadataDetails( &dict, "DesktopEntry", DesktopPath );
const char * SupportedUriSchemes[] = { "file", "http", "https", "smb", "sftp", "cdda", NULL };
FillMetadataDetails( &dict, "SupportedUriSchemes", SupportedUriSchemes );
FillMetadataDetails( &dict, "SupportedMimeTypes", GetSupportedMimeTypes() );
dbus_message_iter_close_container( &args, &dict );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Player" ) )
{
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
////////////////////////////////////////////////////////////////////////
const char * PlaybackStatus;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlaybackStatus = "Stopped";
else if( State == guMEDIASTATE_PAUSED )
PlaybackStatus = "Paused";
else //if( State == guMEDIASTATE_PLAYING )
PlaybackStatus = "Playing";
FillMetadataDetails( &dict, "PlaybackStatus", PlaybackStatus );
////////////////////////////////////////////////////////////////////////
const char * LoopStatus;
int PlayLoop = m_PlayerPanel->GetPlayMode();
if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_TRACK )
LoopStatus = "Track";
else if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_PLAYLIST )
LoopStatus = "Playlist";
else //if( PlayLoop == guPLAYER_PLAYMODE_NONE )
LoopStatus = "None";
FillMetadataDetails( &dict, "LoopStatus", LoopStatus );
////////////////////////////////////////////////////////////////////////
double Rate = 1.0;
FillMetadataDetails( &dict, "Rate", Rate );
////////////////////////////////////////////////////////////////////////
dbus_bool_t Shuffle = false;
FillMetadataDetails( &dict, "Shuffle", Shuffle );
////////////////////////////////////////////////////////////////////////
const guCurrentTrack * CurTrack = m_PlayerPanel->GetCurrentTrack();
FillMetadataDetails( &dict, "Metadata", CurTrack, m_PlayerPanel->GetCurrentItem() );
////////////////////////////////////////////////////////////////////////
double CurVolume = m_PlayerPanel->GetVolume() / 100;
FillMetadataDetails( &dict, "Volume", CurVolume );
////////////////////////////////////////////////////////////////////////
gint64 CurPosition = m_PlayerPanel->GetPosition() * 1000;
FillMetadataDetails( &dict, "Position", CurPosition );
////////////////////////////////////////////////////////////////////////
FillMetadataDetails( &dict, "MinimumRate", Rate );
////////////////////////////////////////////////////////////////////////
FillMetadataDetails( &dict, "MaximumRate", Rate );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanGoNext = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_GO_NEXT ) > 0;
FillMetadataDetails( &dict, "CanGoNext", CanGoNext );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanGoPrev = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_GO_PREV ) > 0;
FillMetadataDetails( &dict, "CanGoPrevious", CanGoPrev );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanPlay = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_PLAY ) > 0;
FillMetadataDetails( &dict, "CanPlay", CanPlay );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanPause = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_PAUSE ) > 0;
FillMetadataDetails( &dict, "CanPause", CanPause );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanSeek = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_SEEK ) > 0;
FillMetadataDetails( &dict, "CanSeek", CanSeek );
////////////////////////////////////////////////////////////////////////
dbus_bool_t CanControl = true;
FillMetadataDetails( &dict, "CanControl", CanControl );
dbus_message_iter_close_container( &args, &dict );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Tracklist" ) )
{
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Playlists" ) )
{
dbus_message_iter_init_append( reply->GetMessage(), &args );
dbus_message_iter_open_container( &args, DBUS_TYPE_ARRAY, "{sv}", &dict );
int PlaylistCount = m_Db->GetPlayListsCount();
FillMetadataDetails( &dict, "PlaylistCount", PlaylistCount );
const char * PlaylistOrders[] = {
"Default",
NULL };
FillMetadataDetails( &dict, "Orderings", PlaylistOrders );
dbus_bool_t plstate = false;
const char * plpath = "/org/mpris/MediaPlayer2/guayadeque/Playlist/0";
const char * plname = "";
const char * plicon = "";
FillMetadataDetails( &dict, "ActivePlaylist", plstate, plpath, plname, plicon );
dbus_message_iter_close_container( &args, &dict );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else
{
const char * QueryIface;
const char * QueryProperty;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_STRING, &QueryIface,
DBUS_TYPE_STRING, &QueryProperty,
DBUS_TYPE_INVALID );
//guLogMessage( wxT( "QIface : %s" ), wxString::FromAscii( QueryIface ).c_str() );
//guLogMessage( wxT( "QProp. : %s" ), wxString::FromAscii( QueryProperty ).c_str() );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the '" GUAYADEQUE_PROPERTIES_INTERFACE "' parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
if( !strcmp( Member, "Get" ) )
{
if( !strcmp( QueryIface, "org.mpris.MediaPlayer2" ) )
{
if( !strcmp( QueryProperty, "CanQuit" ) )
{
dbus_bool_t ReplyVal = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &ReplyVal ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Fullscreen" ) )
{
guMainFrame * MainFrame = guMainFrame::GetMainFrame();
dbus_bool_t FullScreen = MainFrame->IsFullScreen();
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &FullScreen ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanSetFullscreen" ) )
{
dbus_bool_t ReplyVal = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &ReplyVal ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanRaise" ) )
{
dbus_bool_t ReplyVal = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &ReplyVal ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "HasTrackList" ) )
{
dbus_bool_t ReplyVal = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &ReplyVal ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Identity" ) )
{
const char * AppName = "Guayadeque Music Player";
if( AddVariant( reply->GetMessage(), DBUS_TYPE_STRING, &AppName ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "DesktopEntry" ) )
{
const char * DesktopPath = "guayadeque";
if( AddVariant( reply->GetMessage(), DBUS_TYPE_STRING, &DesktopPath ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "SupportedUriSchemes" ) )
{
const char * SupportedUriSchemes[] = { "file", "http", "smb", "sftp", "cdda", NULL };
if( AddVariant( reply->GetMessage(), DBUS_TYPE_ARRAY, &SupportedUriSchemes ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "SupportedMimeTypes" ) )
{
if( AddVariant( reply->GetMessage(), DBUS_TYPE_ARRAY, GetSupportedMimeTypes() ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Player" ) )
{
//guLogMessage( wxT( "Query: '%s'" ), QueryProperty );
if( !strcmp( QueryProperty, "PlaybackStatus" ) )
{
const char * PlaybackStatus;
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_STOPPED )
PlaybackStatus = "Stopped";
else if( State == guMEDIASTATE_PAUSED )
PlaybackStatus = "Paused";
else //if( State == guMEDIASTATE_PLAYING )
PlaybackStatus = "Playing";
if( AddVariant( reply->GetMessage(), DBUS_TYPE_STRING, &PlaybackStatus ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "LoopStatus" ) )
{
const char * LoopStatus;
int PlayLoop = m_PlayerPanel->GetPlayLoop();
if( PlayLoop == guPLAYER_PLAYMODE_NONE )
LoopStatus = "None";
else if( PlayLoop == guPLAYER_PLAYMODE_REPEAT_TRACK )
LoopStatus = "Track";
else //if( PlayLoop == guPLAYER_PLAYLOOP_PLAYLIST )
LoopStatus = "Playlist";
if( AddVariant( reply->GetMessage(), DBUS_TYPE_STRING, &LoopStatus ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Rate" ) )
{
double Rate = 1.0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_DOUBLE, &Rate ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Shuffle" ) )
{
dbus_bool_t Shuffle = false;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &Shuffle ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Metadata" ) )
{
const guCurrentTrack * CurTrack = m_PlayerPanel->GetCurrentTrack();
FillMetadataArgs( reply, CurTrack, m_PlayerPanel->GetCurrentItem() );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( QueryProperty, "Volume" ) )
{
double CurVolume = m_PlayerPanel->GetVolume() / 100;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_DOUBLE, &CurVolume ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Position" ) )
{
gint64 CurPosition = m_PlayerPanel->GetPosition() * 1000;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_INT64, &CurPosition ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "MinimumRate" ) )
{
double Rate = 1.0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_DOUBLE, &Rate ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "MaximumRate" ) )
{
double Rate = 1.0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_DOUBLE, &Rate ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanGoNext" ) )
{
dbus_bool_t CanGoNext = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_GO_NEXT ) > 0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanGoNext ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanGoPreviouss" ) )
{
dbus_bool_t CanGoPrev = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_GO_PREV ) > 0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanGoPrev ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanPlay" ) )
{
dbus_bool_t CanPlay = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_PLAY ) > 0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanPlay ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanPause" ) )
{
dbus_bool_t CanPause = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_PAUSE ) > 0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanPause ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanSeek" ) )
{
dbus_bool_t CanSeek = ( m_PlayerPanel->GetCaps() & MPRIS_CAPS_CAN_SEEK ) > 0;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanSeek ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "CanControl" ) )
{
dbus_bool_t CanControl = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanControl ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.TrackList" ) )
{
if( !strcmp( QueryProperty, "Tracks" ) )
{
}
else if( !strcmp( QueryProperty, "CanEditTracks" ) )
{
dbus_bool_t CanEdit = true;
if( AddVariant( reply->GetMessage(), DBUS_TYPE_BOOLEAN, &CanEdit ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Playlists" ) )
{
if( !strcmp( QueryProperty, "PlaylistCount" ) )
{
}
else if( !strcmp( QueryProperty, "Orderings" ) )
{
}
else if( !strcmp( QueryProperty, "ActivePlaylist" ) )
{
}
}
}
else if( !strcmp( Member, "Set" ) )
{
if( !strcmp( QueryIface, "org.mpris.MediaPlayer2" ) )
{
if( !strcmp( QueryProperty, "Fullscreen" ) )
{
dbus_bool_t FullScreen;
if( GetVariant( msg->GetMessage(), DBUS_TYPE_BOOLEAN, &FullScreen ) )
{
guMainFrame * MainFrame = guMainFrame::GetMainFrame();
wxCommandEvent event( wxEVT_MENU, ID_MENU_VIEW_FULLSCREEN );
event.SetInt( FullScreen );
wxPostEvent( MainFrame, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( QueryIface, "org.mpris.MediaPlayer2.Player" ) )
{
if( !strcmp( QueryProperty, "LoopStatus" ) )
{
const char * LoopStatus;
if( GetVariant( msg->GetMessage(), DBUS_TYPE_STRING, &LoopStatus ) )
{
int PlayLoop;
if( !strcmp( LoopStatus, "None" ) )
{
PlayLoop = guPLAYER_PLAYMODE_NONE;
}
else if( !strcmp( LoopStatus, "Track" ) )
{
PlayLoop = guPLAYER_PLAYMODE_REPEAT_TRACK;
}
else //if( !strcmp( LoopStatus, "Playlist" ) )
{
PlayLoop = guPLAYER_PLAYMODE_REPEAT_PLAYLIST;
}
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETLOOP );
event.SetInt( PlayLoop );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( QueryProperty, "Rate" ) )
{
// We are not going to support rate
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( QueryProperty, "Shuffle" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETRANDOM );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( QueryProperty, "Volume" ) )
{
double Volume;
if( GetVariant( msg->GetMessage(), DBUS_TYPE_DOUBLE, &Volume ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_SETVOLUME );
event.SetInt( ( int ) ( Volume * 100 ) );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
}
}
}
}
}
else if( !strcmp( Interface, GUAYADEQUE_MPRIS2_INTERFACE_ROOT ) )
{
if( !strcmp( Path, GUAYADEQUE_MPRIS2_OBJECT_PATH ) )
{
if( !strcmp( Member, "Raise" ) )
{
wxCommandEvent RaiseCmd( wxEVT_MENU, ID_MAINFRAME_WINDOW_RAISE );
wxPostEvent( guMainFrame::GetMainFrame(), RaiseCmd );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Quit" ) )
{
wxCommandEvent QuitCmd( wxEVT_MENU, ID_MENU_QUIT );
wxPostEvent( guMainFrame::GetMainFrame(), QuitCmd );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( Interface, GUAYADEQUE_MPRIS2_INTERFACE_PLAYER ) )
{
if( !strcmp( Path, GUAYADEQUE_MPRIS2_OBJECT_PATH ) )
{
if( !strcmp( Member, "Next" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_NEXTTRACK );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Previous" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PREVTRACK );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "NextAlbum" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_NEXTALBUM );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "PreviousAlbum" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PREVALBUM );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Pause" ) )
{
if( m_PlayerPanel->GetState() == guMEDIASTATE_PLAYING )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "PlayPause" ) )
{
//if( m_PlayerPanel->GetState() == guMediaState_PLAYING )
//{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
//}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Stop" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_STOP );
wxPostEvent( m_PlayerPanel, event );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Play" ) )
{
if( m_PlayerPanel->GetState() != guMEDIASTATE_PLAYING )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
}
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "Seek" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_int64_t Position;
dbus_message_get_args( msg->GetMessage(), &error, DBUS_TYPE_INT64, &Position, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the Position parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
m_PlayerPanel->SetPosition( Position / 1000 );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( !strcmp( Member, "SetPosition" ) )
{
DBusError error;
dbus_error_init( &error );
const char * TrackId;
dbus_int64_t Position;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_OBJECT_PATH, &TrackId,
DBUS_TYPE_INT64, &Position,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the Position parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
if( wxString::Format( wxT( "/org/mpris/MediaPlayer2/Track/%u" ), m_PlayerPanel->GetCurrentItem() ) == wxString( TrackId, wxConvUTF8 ) )
{
m_PlayerPanel->SetPosition( Position / 1000 );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( Member, "OpenUri" ) )
{
DBusError error;
dbus_error_init( &error );
const char * Uri;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_STRING, &Uri,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the OpenUri parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
wxArrayString Streams;
Streams.Add( wxString( Uri, wxConvUTF8 ) );
m_PlayerPanel->SetPlayList( Streams );
}
}
}
}
else if( !strcmp( Interface, GUAYADEQUE_MPRIS2_INTERFACE_TRACKLIST ) )
{
if( !strcmp( Path, GUAYADEQUE_MPRIS2_OBJECT_PATH ) )
{
if( !strcmp( Member, "GetTracksMetadata" ) )
{
}
else if( !strcmp( Member, "AddTrack" ) )
{
}
else if( !strcmp( Member, "RemoveTrack" ) )
{
}
else if( !strcmp( Member, "GoTo" ) )
{
}
}
}
else if( !strcmp( Interface, GUAYADEQUE_MPRIS2_INTERFACE_PLAYLISTS ) )
{
if( !strcmp( Path, GUAYADEQUE_MPRIS2_OBJECT_PATH ) )
{
if( !strcmp( Member, "ActivatePlaylist" ) )
{
DBusError error;
dbus_error_init( &error );
const char * PlaylistPath;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_OBJECT_PATH, &PlaylistPath,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the ActivatePlaylist parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
wxString PlaylistName = wxString( PlaylistPath, wxConvUTF8 ).AfterLast( wxT( '/' ) );
long PlaylistId;
if( PlaylistName.ToLong( &PlaylistId ) )
{
// Send Event to the PlayerPanel to load the playlist
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MAINFRAME_LOAD_PLAYLIST );
CmdEvent.SetInt( PlaylistId );
wxPostEvent( guMainFrame::GetMainFrame(), CmdEvent );
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
else if( !strcmp( Member, "GetPlaylists" ) )
{
DBusError error;
dbus_error_init( &error );
dbus_uint32_t Index;
dbus_uint32_t MaxCount;
const char * Order;
dbus_bool_t ReverseOrder;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_UINT32, &Index,
DBUS_TYPE_UINT32, &MaxCount,
DBUS_TYPE_STRING, &Order,
DBUS_TYPE_BOOLEAN, &ReverseOrder,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Could not read the GetPlaylists parameter : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
if( GetPlaylists( reply->GetMessage(), Index, MaxCount, Order, ReverseOrder ) )
{
Send( reply );
Flush();
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
}
}
}
return RetVal;
}
#define INDICATORS_SOUND_RETRY_COUNT 10
#define INDICATORS_SOUND_WAIT_TIME 100
// -------------------------------------------------------------------------------- //
int guMPRIS2::Indicators_Sound_BlacklistMediaPlayer( const dbus_bool_t blacklist )
{
int RetryCnt = 0;
guDBusMethodCall * Msg = new guDBusMethodCall( "com.canonical.indicators.sound",
"/com/canonical/indicators/sound/service",
"com.canonical.indicators.sound",
"BlacklistMediaPlayer" );
const char * desktopname = "guayadeque";
int RetVal = wxNOT_FOUND;
dbus_message_append_args( Msg->GetMessage(), DBUS_TYPE_STRING, &desktopname, DBUS_TYPE_BOOLEAN, &blacklist, DBUS_TYPE_INVALID );
guDBusMessage * Reply = NULL;
do {
Reply = SendWithReplyAndBlock( Msg );
if( Reply )
{
DBusError error;
dbus_error_init( &error );
dbus_bool_t Changed = false;
dbus_message_get_args( Reply->GetMessage(), &error, DBUS_TYPE_BOOLEAN, &Changed, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Indicator Sound parameter error : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
RetVal = Changed;
}
delete Reply;
}
else
{
if( RetryCnt++ > INDICATORS_SOUND_RETRY_COUNT )
break;
wxMilliSleep( INDICATORS_SOUND_WAIT_TIME );
}
} while( !Reply );
delete Msg;
guLogMessage( wxT( "Indicators_Sound_BlacklistMediaPlayer( %i ) => %i" ), blacklist, RetVal );
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guMPRIS2::Indicators_Sound_IsBlackListed( void )
{
int RetryCnt = 0;
int RetVal = wxNOT_FOUND;
guDBusMethodCall * Msg = new guDBusMethodCall( "com.canonical.indicators.sound",
"/com/canonical/indicators/sound/service",
"com.canonical.indicators.sound",
"IsBlacklisted" );
const char * desktopname = "guayadeque";
dbus_message_append_args( Msg->GetMessage(), DBUS_TYPE_STRING, &desktopname, DBUS_TYPE_INVALID );
guDBusMessage * Reply = NULL;
do {
Reply = SendWithReplyAndBlock( Msg );
if( Reply )
{
DBusError error;
dbus_error_init( &error );
dbus_bool_t Blacklisted = false;
dbus_message_get_args( Reply->GetMessage(), &error, DBUS_TYPE_BOOLEAN, &Blacklisted, DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
guLogMessage( wxT( "Indicator Sound parameter error : %s" ), wxString( error.message, wxConvUTF8 ).c_str() );
dbus_error_free( &error );
}
else
{
RetVal = Blacklisted;
}
delete Reply;
}
else
{
if( RetryCnt++ > INDICATORS_SOUND_RETRY_COUNT )
break;
wxMilliSleep( INDICATORS_SOUND_WAIT_TIME );
}
} while( !Reply );
delete Msg;
guLogMessage( wxT( "Indicators_Sound_IsBlacklisted() => %i" ), RetVal );
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guMPRIS2::Indicators_Sound_Available( void )
{
bool RetVal = HasOwner( "com.canonical.indicators.sound" );
guLogMessage( wxT( "Indicators_Sound_Available() => %i" ), RetVal );
return RetVal;
}
}
// -------------------------------------------------------------------------------- //
| 84,312
|
C++
|
.cpp
| 1,623
| 34.536044
| 196
| 0.45682
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,558
|
gudbus.cpp
|
anonbeat_guayadeque/src/dbus/gudbus.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "gudbus.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
DBusHandlerResult Handle_Messages( DBusConnection * conn, DBusMessage * msg, void * udata )
{
guDBusServer * DBusObj = ( guDBusServer * ) udata;
//guDBusMessage * Msg = new guDBusMessage( msg );
guDBusMessage * Msg = new guDBusMessage( msg );
guDBusMethodReturn * Reply = NULL;
if( Msg->NeedReply() )
{
Reply = new guDBusMethodReturn( msg );
}
DBusHandlerResult RetVal = DBusObj->HandleMessages( Msg, Reply );
//printf( "*** End of handle_messages ***\n" );
delete Msg;
if( Reply )
delete Reply;
return RetVal;
}
// -------------------------------------------------------------------------------- //
void Handle_Response( DBusPendingCall * PCall, void * udata )
{
guDBusClient * DBusObj = ( guDBusClient * ) udata;
DBusMessage * reply;
reply = dbus_pending_call_steal_reply( PCall );
guDBusMessage * Msg = new guDBusMessage( reply );
DBusObj->HandleMessages( Msg, NULL );
delete Msg;
dbus_message_unref( reply );
dbus_pending_call_unref( PCall );
}
// -------------------------------------------------------------------------------- //
guDBusServer::guDBusServer( const char * name, bool System )
{
dbus_error_init( &m_DBusErr );
m_DBusThread = NULL;
m_DBusConn = dbus_bus_get( System ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &m_DBusErr );
if( dbus_error_is_set( &m_DBusErr ) )
{
guLogError( wxT( "Get DBus object failed : %s" ), m_DBusErr.message );
dbus_error_free( &m_DBusErr );
}
if( m_DBusConn )
{
if( name )
{
RequestName( name );
}
if( dbus_connection_add_filter( m_DBusConn, Handle_Messages, ( void * ) this, NULL ) )
{
m_DBusThread = new guDBusThread( this );
}
}
}
// -------------------------------------------------------------------------------- //
guDBusServer::~guDBusServer()
{
if( m_Clients.Count() )
{
while( m_Clients.Count() )
{
guDBusClient * Client = m_Clients.Last();
delete Client;
}
}
if( m_DBusThread )
{
m_DBusThread->Pause();
m_DBusThread->Delete();
}
if( m_DBusConn )
{
//dbus_connection_close( m_DBusConn );
dbus_connection_unref( m_DBusConn );
}
}
// -------------------------------------------------------------------------------- //
DBusConnection * guDBusServer::GetConnection()
{
return m_DBusConn;
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::HasOwner( const char * name )
{
return dbus_bus_name_has_owner( m_DBusConn, name, NULL );
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::RequestName( const char * name )
{
wxASSERT( name );
dbus_bus_request_name( m_DBusConn, name, DBUS_NAME_FLAG_REPLACE_EXISTING, &m_DBusErr );
if( dbus_error_is_set( &m_DBusErr ) )
{
guLogError( wxT( "Request name '%s' failed : %s" ), name, m_DBusErr.message );
dbus_error_free( &m_DBusErr );
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guDBusServer::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
wxASSERT( msg );
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
int count = m_Clients.Count();
for( int index = 0; index < count; index++ )
{
m_ClientsMutex.Lock();
if( m_Clients[ index ]->HandleMessages( msg, reply ) == DBUS_HANDLER_RESULT_HANDLED )
{
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
m_ClientsMutex.Unlock();
if( RetVal == DBUS_HANDLER_RESULT_HANDLED )
break;
}
// delete msg;
//
// if( reply )
// delete reply;
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::RegisterObjectPath( const char * objname )
{
DBusObjectPathVTable VTable = { NULL, Handle_Messages, NULL, NULL, NULL, NULL };
return dbus_connection_register_object_path( m_DBusConn, objname, &VTable, this );
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::UnRegisterObjectPath( const char * objname )
{
return dbus_connection_unregister_object_path( m_DBusConn, objname );
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::AddMatch( const char * rule )
{
DBusError error;
dbus_error_init( &error );
dbus_bus_add_match( m_DBusConn, rule, &error );
if( dbus_error_is_set( &error ) )
{
guLogError( wxT( "Could not add the match %s : %s" ),
wxString::FromAscii( rule ).c_str(),
wxString::FromAscii( error.message ).c_str() );
dbus_error_free( &error );
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::Send( guDBusMessage * msg )
{
return msg && dbus_connection_send( m_DBusConn, msg->GetMessage(), NULL );
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::SendWithReply( guDBusMessage * msg, guDBusClient * client, int timeout )
{
DBusPendingCall * PCall = NULL;
bool RetVal = dbus_connection_send_with_reply( m_DBusConn, msg->GetMessage(), &PCall, timeout );
dbus_pending_call_set_notify( PCall, Handle_Response, (void *) client, NULL );
return RetVal;
}
// -------------------------------------------------------------------------------- //
guDBusMessage * guDBusServer::SendWithReplyAndBlock( guDBusMessage * msg, int timeout )
{
DBusError error;
dbus_error_init( &error );
guDBusMessage * Reply;
DBusMessage * Result = dbus_connection_send_with_reply_and_block( m_DBusConn, msg->GetMessage(), timeout, &error );
Reply = Result ? new guDBusMessage( Result ) : NULL;
// if( Result )
// dbus_message_unref( Result );
return Reply;
}
// -------------------------------------------------------------------------------- //
void guDBusServer::Flush()
{
dbus_connection_flush( m_DBusConn );
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::RegisterClient( guDBusClient * client )
{
wxMutexLocker Locker( m_ClientsMutex );
if( m_Clients.Index( client ) == wxNOT_FOUND )
{
m_Clients.Add( client );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDBusServer::UnRegisterClient( guDBusClient * client )
{
wxMutexLocker Locker( m_ClientsMutex );
if( m_Clients.Index( client ) != wxNOT_FOUND )
{
m_Clients.Remove( client );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
void guDBusServer::Run()
{
m_DBusThread->Run();
}
// -------------------------------------------------------------------------------- //
// guDBusClient
// -------------------------------------------------------------------------------- //
guDBusClient::guDBusClient( guDBusServer * server )
{
wxASSERT( server );
m_DBusServer = server;
}
// -------------------------------------------------------------------------------- //
guDBusClient::~guDBusClient()
{
UnRegisterClient();
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::HasOwner( const char * name )
{
return m_DBusServer->HasOwner( name );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::RegisterClient( void )
{
return m_DBusServer->RegisterClient( this );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::UnRegisterClient( void )
{
return m_DBusServer->UnRegisterClient( this );
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guDBusClient::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::RequestName( const char * name )
{
return m_DBusServer->RequestName( name );
}
// -------------------------------------------------------------------------------- //
DBusConnection * guDBusClient::GetConnection()
{
return m_DBusServer->GetConnection();
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::RegisterObjectPath( const char * objname )
{
return m_DBusServer->RegisterObjectPath( objname );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::UnRegisterObjectPath( const char * objname )
{
return m_DBusServer->UnRegisterObjectPath( objname );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::AddMatch( const char * rule )
{
return m_DBusServer->AddMatch( rule );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::Send( guDBusMessage * msg )
{
return m_DBusServer->Send( msg );
}
// -------------------------------------------------------------------------------- //
bool guDBusClient::SendWithReply( guDBusMessage * msg, int timeout )
{
return m_DBusServer->SendWithReply( msg, this, timeout );
}
// -------------------------------------------------------------------------------- //
guDBusMessage * guDBusClient::SendWithReplyAndBlock( guDBusMessage * msg, int timeout )
{
return m_DBusServer->SendWithReplyAndBlock( msg, timeout );
}
// -------------------------------------------------------------------------------- //
void guDBusClient::Flush()
{
m_DBusServer->Flush();
}
// -------------------------------------------------------------------------------- //
// guDBusMessage
// -------------------------------------------------------------------------------- //
guDBusMessage::guDBusMessage( int type )
{
// types can be :
// DBUS_MESSAGE_TYPE_INVALID
// DBUS_MESSAGE_TYPE_METHOD_CALL
// DBUS_MESSAGE_TYPE_METHOD_RETURN
// DBUS_MESSAGE_TYPE_ERROR
// DBUS_MESSAGE_TYPE_SIGNAL
m_DBusMsg = dbus_message_new( type );
}
// -------------------------------------------------------------------------------- //
guDBusMessage::guDBusMessage( guDBusMessage * msg )
{
//m_DBusMsg = dbus_message_copy( msg->GetMessage() );
m_DBusMsg = msg->GetMessage();
dbus_message_ref( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
guDBusMessage::guDBusMessage( DBusMessage * msg )
{
//m_DBusMsg = dbus_message_copy( msg );
m_DBusMsg = msg;
dbus_message_ref( msg );
}
// -------------------------------------------------------------------------------- //
guDBusMessage::~guDBusMessage()
{
if( m_DBusMsg )
{
dbus_message_unref( m_DBusMsg );
}
}
// -------------------------------------------------------------------------------- //
DBusMessage * guDBusMessage::GetMessage()
{
return m_DBusMsg;
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetErrorName()
{
return dbus_message_get_error_name( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetInterface()
{
return dbus_message_get_interface( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetMember()
{
return dbus_message_get_member( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::NeedReply()
{
return !dbus_message_get_no_reply( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
void guDBusMessage::SetNoReply( const bool needreply )
{
dbus_message_set_no_reply( m_DBusMsg, needreply );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetPath()
{
return dbus_message_get_path( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
unsigned int guDBusMessage::GetReplySerial()
{
return dbus_message_get_reply_serial( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetSender()
{
return dbus_message_get_sender( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetDestination()
{
return dbus_message_get_destination( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
unsigned int guDBusMessage::GetSerial()
{
return dbus_message_get_serial( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
int guDBusMessage::GetType()
{
return dbus_message_get_type( m_DBusMsg );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::HasDestination( const char * dest )
{
return dbus_message_has_destination( m_DBusMsg, dest );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::HasInterface( const char * iface )
{
return dbus_message_has_interface( m_DBusMsg, iface );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::HasMember( const char * member )
{
return dbus_message_has_member( m_DBusMsg, member );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::HasPath( const char * path )
{
return dbus_message_has_path( m_DBusMsg, path );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::HasSender( const char * sender )
{
return dbus_message_has_sender( m_DBusMsg, sender );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::IsError( const char * errname )
{
return dbus_message_is_error( m_DBusMsg, errname );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::IsMethodCall( const char * iface, const char * method )
{
return dbus_message_is_method_call( m_DBusMsg, iface, method );
}
// -------------------------------------------------------------------------------- //
bool guDBusMessage::IsSignal( const char * iface, const char * signal_name )
{
return dbus_message_is_signal( m_DBusMsg, iface, signal_name );
}
// -------------------------------------------------------------------------------- //
const char * guDBusMessage::GetObjectPath()
{
const char * RetVal;
if( !dbus_message_get_args( m_DBusMsg, NULL, DBUS_TYPE_OBJECT_PATH, &RetVal, DBUS_TYPE_INVALID ) )
return NULL;
return RetVal;
}
// -------------------------------------------------------------------------------- //
// guDBusMethodCall
// -------------------------------------------------------------------------------- //
guDBusMethodCall::guDBusMethodCall( const char * dest, const char * path, const char *iface, const char * method )
{
m_DBusMsg = dbus_message_new_method_call( dest, path, iface, method );
}
// -------------------------------------------------------------------------------- //
// guDBusMethodReturn
// -------------------------------------------------------------------------------- //
guDBusMethodReturn::guDBusMethodReturn( guDBusMessage * msg )
{
m_DBusMsg = dbus_message_new_method_return( msg->GetMessage() );
}
// -------------------------------------------------------------------------------- //
guDBusMethodReturn::guDBusMethodReturn( DBusMessage * msg )
{
m_DBusMsg = dbus_message_new_method_return( msg );
}
// -------------------------------------------------------------------------------- //
guDBusSignal::guDBusSignal( const char * path, const char * iface, const char * name )
{
m_DBusMsg = dbus_message_new_signal( path, iface, name );
}
// -------------------------------------------------------------------------------- //
// guDBusThread
// -------------------------------------------------------------------------------- //
guDBusThread::guDBusThread( guDBusServer * dbusowner ) : wxThread( wxTHREAD_DETACHED )
{
m_DBusOwner = dbusowner;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY );
//Run();
}
}
// -------------------------------------------------------------------------------- //
guDBusThread::~guDBusThread()
{
}
// -------------------------------------------------------------------------------- //
guDBusThread::ExitCode guDBusThread::Entry()
{
while( !TestDestroy() )
{
dbus_connection_read_write_dispatch( m_DBusOwner->GetConnection(), 0 );
Sleep( guDBUS_THREAD_IDLE_TIMEOUT );
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 18,791
|
C++
|
.cpp
| 502
| 34.326693
| 119
| 0.450758
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,559
|
mmkeys.cpp
|
anonbeat_guayadeque/src/dbus/mmkeys.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "mmkeys.h"
#include "EventCommandIds.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guMMKeys::guMMKeys( guDBusServer * server, guPlayerPanel * playerpanel ) : guDBusClient( server )
{
m_PlayerPanel = playerpanel;
RegisterClient();
// Support for the MultimediaKeys
// AddMatch( "type='signal',interface='org.gnome.SettingsDaemon'" );
AddMatch( "type='signal',interface='org.gnome.SettingsDaemon.MediaKeys'" );
GrabMediaPlayerKeys( 0 );
}
// -------------------------------------------------------------------------------- //
guMMKeys::~guMMKeys()
{
ReleaseMediaPlayerKeys();
}
// -------------------------------------------------------------------------------- //
void guMMKeys::GrabMediaPlayerKeys( const unsigned int time )
{
guDBusMethodCall * Msg = new guDBusMethodCall( "org.gnome.SettingsDaemon",
"/org/gnome/SettingsDaemon/MediaKeys",
"org.gnome.SettingsDaemon.MediaKeys",
"GrabMediaPlayerKeys" );
const char * AppId = "Guayadeque";
dbus_message_append_args( Msg->GetMessage(),
DBUS_TYPE_STRING, &AppId,
DBUS_TYPE_UINT32, &time,
DBUS_TYPE_INVALID );
SendWithReply( Msg );
delete Msg;
}
// -------------------------------------------------------------------------------- //
void guMMKeys::ReleaseMediaPlayerKeys( void )
{
guDBusMethodCall * Msg = new guDBusMethodCall( "org.gnome.SettingsDaemon",
"/org/gnome/SettingsDaemon/MediaKeys",
"org.gnome.SettingsDaemon.MediaKeys",
"ReleaseMediaPlayerKeys" );
const char * AppId = "Guayadeque";
dbus_message_append_args( Msg->GetMessage(),
DBUS_TYPE_STRING, &AppId,
DBUS_TYPE_INVALID );
SendWithReply( Msg );
delete Msg;
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guMMKeys::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
wxASSERT( msg );
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
//const char * Interface = msg->GetInterface();
const char * Member = msg->GetMember();
int Type = msg->GetType();
const char * Path = msg->GetPath();
// MULTIMEDIA KEYS
if( Type == DBUS_MESSAGE_TYPE_SIGNAL ) // If its a Signal message
{
//guLogMessage( wxT( "**** Received Signal ****\n" )
// wxT( "Path : '%s'\n" )
// wxT( "Member : '%s'" ),
// wxString( Path, wxConvUTF8 ).c_str(),
// wxString( Member, wxConvUTF8 ).c_str()
// );
if( !strcmp( Path, "/org/gnome/SettingsDaemon/MediaKeys" ) )
{
if( !strcmp( Member, "MediaPlayerKeyPressed" ) )
{
DBusError error;
dbus_error_init( &error );
const char * s = NULL;
const char * KeyName = NULL;
dbus_message_get_args( msg->GetMessage(), &error,
DBUS_TYPE_STRING, &s,
DBUS_TYPE_STRING, &KeyName,
DBUS_TYPE_INVALID );
if( dbus_error_is_set( &error ) )
{
printf( "Could not read the MediaPlayerKeyPressed parameters : %s\n", error.message );
dbus_error_free( &error );
//RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
else
{
if( !strcmp( KeyName, "Play" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( KeyName, "Stop" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_STOP );
wxPostEvent( m_PlayerPanel, event );
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( KeyName, "Previous" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PREVTRACK );
wxPostEvent( m_PlayerPanel, event );
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( KeyName, "Next" ) )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_NEXTTRACK );
wxPostEvent( m_PlayerPanel, event );
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( KeyName, "Pause" ) )
{
if( m_PlayerPanel->GetState() == guMEDIASTATE_PLAYING )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
wxPostEvent( m_PlayerPanel, event );
}
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
}
}
return RetVal;
}
}
// -------------------------------------------------------------------------------- //
| 6,553
|
C++
|
.cpp
| 148
| 33.344595
| 106
| 0.483618
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,560
|
notify.cpp
|
anonbeat_guayadeque/src/dbus/notify.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "notify.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guDBusNotify::guDBusNotify( guDBusServer * server ) : guDBusClient( server )
{
m_MsgId = 0;
RegisterClient();
}
// -------------------------------------------------------------------------------- //
guDBusNotify::~guDBusNotify()
{
if( m_MsgId )
{
//guLogMessage( wxT( "Sending Close Message... %i" ), m_MsgId );
// guDBusMethodCall * Msg = new guDBusMethodCall( "org.freedesktop.Notifications",
// "/org/freedesktop/Notifications",
// "org.freedesktop.Notifications",
// "CloseNotification" );
// dbus_message_append_args( Msg->GetMessage(), DBUS_TYPE_UINT32, &m_MsgId, DBUS_TYPE_INVALID );
// Msg->SetNoReply( true );
// Send( Msg );
//
// delete Msg;
}
}
// -------------------------------------------------------------------------------- //
// Its done this way to avoid the warning of temporary address
void inline Append_String( DBusMessageIter * iter, const char * str )
{
dbus_message_iter_append_basic( iter, DBUS_TYPE_STRING, &str );
}
// -------------------------------------------------------------------------------- //
void guDBusNotify::Notify( const wxString &icon, const wxString &summary,
const wxString &body, wxImage * image, bool newnotify )
{
guDBusMethodCall * Msg = new guDBusMethodCall( "org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
"Notify");
const char * msg_app = "guayadeque-music-player";
int msg_timeout = -1; // Default timeout
int msg_newid = 0;
DBusMessageIter iter;
DBusMessageIter array;
DBusMessageIter dict;
DBusMessageIter value;
DBusMessageIter variant;
DBusMessageIter data;
dbus_message_iter_init_append( Msg->GetMessage(), &iter );
dbus_message_iter_append_basic( &iter, DBUS_TYPE_STRING, &msg_app );
dbus_message_iter_append_basic( &iter, DBUS_TYPE_UINT32, newnotify ? &msg_newid : &m_MsgId );
//Append_String( &iter, icon.char_str() );
//Append_String( &iter, summary.char_str() );
//Append_String( &iter, body.char_str() );
Append_String( &iter, icon.mb_str( wxConvUTF8 ) );
Append_String( &iter, summary.mb_str( wxConvUTF8 ) );
Append_String( &iter, body.mb_str( wxConvUTF8 ) );
dbus_message_iter_open_container( &iter, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &array );
dbus_message_iter_close_container( &iter, &array );
dbus_message_iter_open_container( &iter, DBUS_TYPE_ARRAY, "{sv}", &array );
if( image )
{
int Width;
int Height;
int Size;
int BitsPerSample;
int Channels;
int BufferSize;
dbus_bool_t HasAlpha;
char * ImageData;
const char * icon_data = "icon_data";
HasAlpha = image->HasAlpha();
Width = image->GetWidth();
Height = image->GetHeight();
Size = Width * 4;
BitsPerSample = 8;
Channels = 4;
BufferSize = Width * Height * 4;
//guLogMessage( wxT( "Has Alpha: %i (%i-%i)" ), HasAlpha, image->GetWidth(), image->GetHeight() );
ImageData = ( char * ) malloc( BufferSize );
unsigned char * adata = NULL;
if( HasAlpha )
adata = image->GetAlpha();
unsigned char * pdata = image->GetData();
int Index = 0;
int DataCnt = 0;
int AlphaCnt = 0;
while( Index < BufferSize )
{
ImageData[ Index++ ] = pdata[ DataCnt++ ];
ImageData[ Index++ ] = pdata[ DataCnt++ ];
ImageData[ Index++ ] = pdata[ DataCnt++ ];
ImageData[ Index++ ] = HasAlpha ? adata[ AlphaCnt++ ] : 255;
}
HasAlpha = true;
dbus_message_iter_open_container( &array, DBUS_TYPE_DICT_ENTRY, 0, &dict );
dbus_message_iter_append_basic( &dict, DBUS_TYPE_STRING, &icon_data );
dbus_message_iter_open_container( &dict, DBUS_TYPE_VARIANT, "(iiibiiay)", &variant );
dbus_message_iter_open_container( &variant, DBUS_TYPE_STRUCT, NULL, &value );
dbus_message_iter_append_basic( &value, DBUS_TYPE_INT32, &Width );
dbus_message_iter_append_basic( &value, DBUS_TYPE_INT32, &Height );
dbus_message_iter_append_basic( &value, DBUS_TYPE_INT32, &Size );
dbus_message_iter_append_basic( &value, DBUS_TYPE_BOOLEAN, &HasAlpha );
dbus_message_iter_append_basic( &value, DBUS_TYPE_INT32, &BitsPerSample );
dbus_message_iter_append_basic( &value, DBUS_TYPE_INT32, &Channels );
dbus_message_iter_open_container( &value, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, &data );
dbus_message_iter_append_fixed_array( &data, DBUS_TYPE_BYTE, &ImageData, BufferSize );
dbus_message_iter_close_container( &value, &data );
dbus_message_iter_close_container( &variant,&value );
dbus_message_iter_close_container( &dict, &variant );
dbus_message_iter_close_container( &array, &dict );
free( ImageData );
}
dbus_message_iter_close_container( &iter, &array );
dbus_message_iter_append_basic( &iter, DBUS_TYPE_INT32, &msg_timeout );
guDBusMessage * Reply = SendWithReplyAndBlock( Msg );
if( Reply )
{
dbus_message_get_args( Reply->GetMessage(), NULL, DBUS_TYPE_UINT32, &m_MsgId, DBUS_TYPE_INVALID );
delete Reply;
}
delete Msg;
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guDBusNotify::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
wxASSERT( msg );
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
// const char * Interface = msg->GetInterface();
const char * Member = msg->GetMember();
int Type = msg->GetType();
// const char * Path = msg->GetPath();
// int Serial = msg->GetSerial();
// int RSerial = msg->GetReplySerial();
// // Show the details of the msg
// guLogMessage( wxT( "==DBusNotify========================" ) );
// guLogMessage( wxT( "Type : %i" ), Type );
// guLogMessage( wxT( "Iface : %s" ), wxString::FromAscii( Interface ).c_str() );
// guLogMessage( wxT( "Path : %s" ), wxString::FromAscii( Path ).c_str() );
// guLogMessage( wxT( "OPath : %s" ), wxString::FromAscii( msg->GetObjectPath() ).c_str() );
// guLogMessage( wxT( "Member : %s" ), wxString::FromAscii( Member ).c_str() );
// guLogMessage( wxT( "Serial : %i" ), Serial );
// guLogMessage( wxT( "RSerial: %i" ), RSerial );
// if( Type == DBUS_MESSAGE_TYPE_METHOD_RETURN )
// {
// dbus_message_get_args( msg->GetMessage(), NULL, DBUS_TYPE_UINT32, &m_MsgId, DBUS_TYPE_INVALID );
// //guLogMessage( wxT( "The Id is: %i" ), m_MsgId );
// RetVal = DBUS_HANDLER_RESULT_HANDLED;
// }
// else if( Type == DBUS_MESSAGE_TYPE_SIGNAL )
if( Type == DBUS_MESSAGE_TYPE_SIGNAL )
{
if( !strcmp( Member, "NotificationClosed" ) )
{
int Id;
int Reason;
if( ( dbus_message_has_signature( msg->GetMessage(), "u" ) &&
dbus_message_get_args( msg->GetMessage(), NULL, DBUS_TYPE_UINT32, &Id, DBUS_TYPE_INVALID ) ) ||
( dbus_message_has_signature( msg->GetMessage(), "uu" ) &&
dbus_message_get_args( msg->GetMessage(), NULL, DBUS_TYPE_UINT32, &Id, DBUS_TYPE_UINT32, &Reason, DBUS_TYPE_INVALID ) ) )
{
if( Id == m_MsgId )
{
m_MsgId = 0;
}
}
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
return RetVal;
}
}
// -------------------------------------------------------------------------------- //
| 9,256
|
C++
|
.cpp
| 195
| 41.133333
| 139
| 0.550587
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,561
|
gsession.cpp
|
anonbeat_guayadeque/src/dbus/gsession.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "gsession.h"
#include "MainFrame.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guGSession::guGSession( guDBusServer * server ) : guDBusClient( server )
{
RegisterClient();
m_ObjectPath = wxEmptyString;
m_Status = guGSESSION_STATUS_REGISTER_CLIENT;
// Support for the MultimediaKeys
guDBusMethodCall * Msg = new guDBusMethodCall( "org.gnome.SessionManager",
"/org/gnome/SessionManager",
"org.gnome.SessionManager",
"RegisterClient" );
const char AppId[] = "guayadeque-music-player";
const char * pAppId = AppId;
wxGetEnv( wxT( "DESKTOP_AUTOSTART_ID" ), &m_ObjectPath );
char AutoStartId[ 1000 ];
strcpy( AutoStartId, m_ObjectPath.char_str() );
const char * pAutoStartId = AutoStartId;
if( !m_ObjectPath.IsEmpty() )
guLogMessage( wxT( "$DESKTOP_AUTOSTART_ID=%s" ), m_ObjectPath.c_str() );
dbus_message_append_args( Msg->GetMessage(),
DBUS_TYPE_STRING, &pAppId,
DBUS_TYPE_STRING, &pAutoStartId,
DBUS_TYPE_INVALID );
SendWithReply( Msg );
delete Msg;
}
// -------------------------------------------------------------------------------- //
guGSession::~guGSession()
{
if( !m_ObjectPath.IsEmpty() && m_Status == guGSESSION_STATUS_INITIALIZED )
{
guDBusMethodCall * Msg = new guDBusMethodCall( "org.gnome.SessionManager",
"/org/gnome/SessionManager",
"org.gnome.SessionManager",
"UnregisterClient" );
const char * pClient = strdup( m_ObjectPath.mb_str() );
dbus_message_append_args( Msg->GetMessage(),
DBUS_TYPE_OBJECT_PATH, &pClient,
DBUS_TYPE_INVALID );
SendWithReply( Msg );
delete pClient;
delete Msg;
}
//guLogMessage( wxT( "Unregistering GSession '%s'" ), m_ObjectPath.c_str() );
}
// -------------------------------------------------------------------------------- //
DBusHandlerResult guGSession::HandleMessages( guDBusMessage * msg, guDBusMessage * reply )
{
wxASSERT( msg );
DBusHandlerResult RetVal = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
// const char * Interface = msg->GetInterface();
const char * Member = msg->GetMember();
int Type = msg->GetType();
const char * Path = msg->GetPath();
// int Serial = msg->GetSerial();
// int RSerial = msg->GetReplySerial();
// // Show the details of the msg
// guLogMessage( wxT( "==GSession========================" ) );
// guLogMessage( wxT( "Type : %i" ), Type );
// guLogMessage( wxT( "Iface : %s" ), wxString::FromAscii( Interface ).c_str() );
// guLogMessage( wxT( "Path : %s" ), wxString::FromAscii( Path ).c_str() );
// guLogMessage( wxT( "OPath : %s" ), wxString::FromAscii( msg->GetObjectPath() ).c_str() );
// guLogMessage( wxT( "Member : %s" ), wxString::FromAscii( Member ).c_str() );
// guLogMessage( wxT( "Serial : %i" ), Serial );
// guLogMessage( wxT( "RSerial: %i" ), RSerial );
if( Type == DBUS_MESSAGE_TYPE_METHOD_RETURN )
{
if( m_Status == guGSESSION_STATUS_REGISTER_CLIENT )
{
m_ObjectPath = wxString::FromAscii( msg->GetObjectPath() );
if( m_ObjectPath.IsEmpty() )
{
guLogError( wxT( "Could not get the GSession Object Path" ) );
m_Status = guGSESSION_STATUS_ERROR;
}
else
{
//guLogMessage( wxT( "Got the GSession Client Id : '%s'" ), m_ObjectPath.c_str() );
// AddMatch( wxString::Format( wxT( "type='signal',"
// "interface='org.gnome.SessionManager.ClientPrivate',"
// "path='%s'" ), m_ObjectPath.c_str() ).char_str() );
m_Status = guGSESSION_STATUS_INITIALIZED;
}
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
else if( Type == DBUS_MESSAGE_TYPE_SIGNAL )
{
if( !strcmp( Path, m_ObjectPath.ToAscii() ) )
{
//guLogMessage( wxT( "Received GSession Client Signal" ) );
if( !strcmp( Member, "Stop" ) )
{
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "QueryEndSession" ) )
{
m_Status = guGSESSION_STATUS_QUERY_END_SESSION;
guDBusMethodCall * MsgCall = new guDBusMethodCall( "org.gnome.SessionManager",
m_ObjectPath.ToAscii(),
NULL,
"EndSessionResponse" );
dbus_bool_t IsOk = true;
const char * Reason = "No reason given";
dbus_message_append_args( MsgCall->GetMessage(),
DBUS_TYPE_BOOLEAN, &IsOk,
DBUS_TYPE_STRING, &Reason,
DBUS_TYPE_INVALID );
SendWithReply( MsgCall );
delete MsgCall;
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
else if( !strcmp( Member, "EndSession" ) )
{
m_Status = guGSESSION_STATUS_END_SESSION;
guDBusMethodCall * MsgCall = new guDBusMethodCall( "org.gnome.SessionManager",
m_ObjectPath.ToAscii(),
NULL,
"EndSessionResponse" );
dbus_bool_t IsOk = true;
const char * Reason = "";
dbus_message_append_args( MsgCall->GetMessage(),
DBUS_TYPE_BOOLEAN, &IsOk,
DBUS_TYPE_STRING, &Reason,
DBUS_TYPE_INVALID );
SendWithReply( MsgCall );
delete MsgCall;
RetVal = DBUS_HANDLER_RESULT_HANDLED;
// Closes the App
guMainFrame::GetMainFrame()->Close( true );
}
else if( !strcmp( Member, "CancelEndSession" ) )
{
RetVal = DBUS_HANDLER_RESULT_HANDLED;
}
}
}
return RetVal;
}
}
// -------------------------------------------------------------------------------- //
| 7,315
|
C++
|
.cpp
| 166
| 35.343373
| 99
| 0.530652
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,562
|
TagInfo.cpp
|
anonbeat_guayadeque/src/taginfo/TagInfo.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TagInfo.h"
#include "Utils.h"
#include "GstTypes.h"
#include "GstTypeFinder.h"
#include "MainFrame.h"
#include "TrackEdit.h"
#include <wx/base64.h>
#include <wx/mstream.h>
#include <wx/tokenzr.h>
#include <wx/wfstream.h>
#include <asfattribute.h>
#include <popularimeterframe.h>
#include <id3v1tag.h>
#include <gst/pbutils/pbutils.h>
namespace Guayadeque {
wxArrayString guSupportedFormats;
wxMutex guSupportedFormatsMutex;
// -------------------------------------------------------------------------------- //
bool guIsGStreamerExt( const wxString &ext )
{
return guGstTypeFinder::getGTF().GetExtensions().Index( ext ) != wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
bool guIsValidAudioFile( const wxString &filename )
{
guSupportedFormatsMutex.Lock();
if( !guSupportedFormats.Count() )
{
guSupportedFormats.Add( wxT( "mp3" ) );
//
guSupportedFormats.Add( wxT( "flac" ) );
//
guSupportedFormats.Add( wxT( "ogg" ) );
guSupportedFormats.Add( wxT( "oga" ) );
//
guSupportedFormats.Add( wxT( "mp4" ) ); // MP4 files
guSupportedFormats.Add( wxT( "m4a" ) );
guSupportedFormats.Add( wxT( "m4b" ) );
guSupportedFormats.Add( wxT( "m4p" ) );
guSupportedFormats.Add( wxT( "aac" ) );
//
guSupportedFormats.Add( wxT( "wma" ) );
guSupportedFormats.Add( wxT( "asf" ) );
//
guSupportedFormats.Add( wxT( "ape" ) );
//
guSupportedFormats.Add( wxT( "wav" ) );
guSupportedFormats.Add( wxT( "aif" ) );
//
guSupportedFormats.Add( wxT( "wv" ) );
//
guSupportedFormats.Add( wxT( "tta" ) );
//
guSupportedFormats.Add( wxT( "mpc" ) );
//
//guSupportedFormats.Add( wxT( "rmj" ) );
guSupportedFormats.Add( wxT( "opus" ) );
}
wxString file_ext = filename.Lower().AfterLast( wxT( '.' ) );
int Position = guSupportedFormats.Index( file_ext );
if( (Position == wxNOT_FOUND) && guIsGStreamerExt( file_ext ) )
Position = INT_MAX;
guSupportedFormatsMutex.Unlock();
return ( Position != wxNOT_FOUND );
}
// -------------------------------------------------------------------------------- //
guTagInfo * guGetTagInfoHandler( const wxString &filename )
{
wxString file_ext = filename.Lower().AfterLast( wxT( '.' ) );
guSupportedFormatsMutex.Lock();
int FormatIndex = guSupportedFormats.Index( file_ext );
guSupportedFormatsMutex.Unlock();
switch( FormatIndex )
{
case 0 : return new guMp3TagInfo( filename );
case 1 : return new guFlacTagInfo( filename );
case 2 :
case 3 :
case 17 : return new guOggTagInfo( filename );
case 4 :
case 5 :
case 6 :
case 7 :
case 8 : return new guMp4TagInfo( filename );
case 9 :
case 10 : return new guASFTagInfo( filename );
#ifdef TAGLIB_WITH_APE_SUPPORT
case 11 : return new guApeTagInfo( filename );
#endif
case 12 :
case 13 : return new guTagInfo( filename );
case 14 : return new guWavPackTagInfo( filename );
case 15 : return new guTrueAudioTagInfo( filename );
case 16 : return new guMpcTagInfo( filename );
//case 17 :
default :
break;
}
if( guIsGStreamerExt( file_ext ) )
return new guGStreamerTagInfo( filename );
return NULL;
}
// -------------------------------------------------------------------------------- //
TagLib::ID3v2::PopularimeterFrame * GetPopM( TagLib::ID3v2::Tag * tag, const TagLib::String &email )
{
TagLib::ID3v2::FrameList PopMList = tag->frameList( "POPM" );
for( TagLib::ID3v2::FrameList::Iterator it = PopMList.begin(); it != PopMList.end(); ++it )
{
TagLib::ID3v2::PopularimeterFrame * PopMFrame = static_cast<TagLib::ID3v2::PopularimeterFrame *>( * it );
//guLogMessage( wxT( "PopM e: '%s' r: %i c: %i" ), TStringTowxString( PopMFrame->email() ).c_str(), PopMFrame->rating(), PopMFrame->counter() );
if( email.isEmpty() || ( PopMFrame->email() == email ) )
{
return PopMFrame;
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
int inline guPopMToRating( const int rating )
{
if( rating < 0 )
return 0;
if( rating == 0 )
return 0;
if( rating < 64 )
return 1;
if( rating < 128 )
return 2;
if( rating < 192 )
return 3;
if( rating < 255 )
return 4;
return 5;
}
// -------------------------------------------------------------------------------- //
int inline guWMRatingToRating( const int rating )
{
if( rating <= 0 )
return 0;
if( rating < 25 )
return 1;
if( rating < 50 )
return 2;
if( rating < 75 )
return 3;
if( rating < 99 )
return 4;
return 5;
}
// -------------------------------------------------------------------------------- //
int inline guRatingToPopM( const int rating )
{
int Ratings[] = { 0, 0, 1, 64, 128, 192, 255 };
guLogMessage( wxT( "Rating: %i => %i" ), rating, Ratings[ rating + 1 ] );
return Ratings[ rating + 1 ];
}
// -------------------------------------------------------------------------------- //
wxImage * GetID3v2ImageType( TagLib::ID3v2::FrameList &framelist,
int frametype = TagLib::ID3v2::AttachedPictureFrame::FrontCover );
wxImage * GetID3v2ImageType( TagLib::ID3v2::FrameList &framelist,
int frametype )
{
TagLib::ID3v2::AttachedPictureFrame * PicFrame;
for( std::list<TagLib::ID3v2::Frame*>::iterator iter = framelist.begin(); iter != framelist.end(); iter++ )
{
PicFrame = static_cast<TagLib::ID3v2::AttachedPictureFrame *>( *iter );
if( ( frametype == wxNOT_FOUND ) || ( PicFrame->type() == frametype ) )
{
int ImgDataSize = PicFrame->picture().size();
if( ImgDataSize > 0 )
{
//guLogMessage( wxT( "ID3v2 header contains APIC frame with %u bytes." ), ImgDataSize );
wxMemoryOutputStream ImgOutStream;
ImgOutStream.Write( PicFrame->picture().data(), ImgDataSize );
wxMemoryInputStream ImgInputStream( ImgOutStream );
wxString ImgHandler = wxString( PicFrame->mimeType().toCString( true ), wxConvUTF8 );
ImgHandler.Replace( wxT( "/jpg" ), wxT( "/jpeg" ) );
wxImage * CoverImage = new wxImage( ImgInputStream, ImgHandler );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
// wxFileOutputStream FOut( wxT( "~/test.jpg" ) );
// FOut.Write( PicFrame->picture().data(), ImgDataSize );
// FOut.Close();
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
wxImage * GetID3v2Image( ID3v2::Tag * tagv2 )
{
TagLib::ID3v2::FrameList FrameList = tagv2->frameListMap()["APIC"];
wxImage * CoverImage = GetID3v2ImageType( FrameList, TagLib::ID3v2::AttachedPictureFrame::FrontCover );
if( !CoverImage )
{
CoverImage = GetID3v2ImageType( FrameList, TagLib::ID3v2::AttachedPictureFrame::Other );
if( !CoverImage )
{
CoverImage = GetID3v2ImageType( FrameList, wxNOT_FOUND );
}
}
return CoverImage;
}
// -------------------------------------------------------------------------------- //
void SetID3v2Image( ID3v2::Tag * tagv2, const wxImage * image )
{
TagLib::ID3v2::AttachedPictureFrame * PicFrame;
TagLib::ID3v2::FrameList FrameList = tagv2->frameListMap()["APIC"];
for( std::list<TagLib::ID3v2::Frame*>::iterator iter = FrameList.begin(); iter != FrameList.end(); iter++ )
{
PicFrame = static_cast<TagLib::ID3v2::AttachedPictureFrame *>( *iter );
// TODO : Ppl should be able to select which image types want guayadeque to remove from the audio files
if( ( PicFrame->type() == TagLib::ID3v2::AttachedPictureFrame::FrontCover ) ||
( PicFrame->type() == TagLib::ID3v2::AttachedPictureFrame::Other ) )
tagv2->removeFrame( PicFrame, TRUE );
}
if( image )
{
PicFrame = new TagLib::ID3v2::AttachedPictureFrame;
PicFrame->setMimeType( "image/jpeg" );
PicFrame->setType( TagLib::ID3v2::AttachedPictureFrame::FrontCover );
wxMemoryOutputStream ImgOutputStream;
if( image->SaveFile( ImgOutputStream, wxBITMAP_TYPE_JPEG ) )
{
ByteVector ImgData( ( TagLib::uint ) ImgOutputStream.GetSize() );
ImgOutputStream.CopyTo( ImgData.data(), ImgOutputStream.GetSize() );
PicFrame->setPicture( ImgData );
tagv2->addFrame( PicFrame );
}
}
}
// -------------------------------------------------------------------------------- //
wxString GetID3v2Lyrics( ID3v2::Tag * tagv2 )
{
TagLib::ID3v2::FrameList frameList = tagv2->frameList( "USLT" );
if( !frameList.isEmpty() )
{
TagLib::ID3v2::UnsynchronizedLyricsFrame * LyricsFrame = static_cast<TagLib::ID3v2::UnsynchronizedLyricsFrame * >( frameList.front() );
if( LyricsFrame )
{
//guLogMessage( wxT( "Found lyrics" ) );
return TStringTowxString( LyricsFrame->text() );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void SetID3v2Lyrics( ID3v2::Tag * tagv2, const wxString &lyrics )
{
//guLogMessage( wxT( "Saving lyrics..." ) );
TagLib::ID3v2::UnsynchronizedLyricsFrame * LyricsFrame;
TagLib::ID3v2::FrameList FrameList = tagv2->frameListMap()["USLT"];
for( std::list<TagLib::ID3v2::Frame*>::iterator iter = FrameList.begin(); iter != FrameList.end(); iter++ )
{
LyricsFrame = static_cast<TagLib::ID3v2::UnsynchronizedLyricsFrame*>( *iter );
tagv2->removeFrame( LyricsFrame, TRUE );
}
if( !lyrics.IsEmpty() )
{
LyricsFrame = new TagLib::ID3v2::UnsynchronizedLyricsFrame( TagLib::String::UTF8 );
LyricsFrame->setText( wxStringToTString( lyrics ) );
tagv2->addFrame( LyricsFrame );
}
}
// -------------------------------------------------------------------------------- //
wxImage * GetXiphCommentCoverArt( Ogg::XiphComment * xiphcomment )
{
if( xiphcomment && xiphcomment->contains( "COVERART" ) )
{
wxString CoverMime = TStringTowxString( xiphcomment->fieldListMap()[ "COVERARTMIME" ].front() );
wxString CoverEncData = TStringTowxString( xiphcomment->fieldListMap()[ "COVERART" ].front() );
//guLogMessage( wxT( "Image:\n%s\n" ), CoverEncData.c_str() );
wxMemoryBuffer CoverDecData = wxBase64Decode( CoverEncData );
//guLogMessage( wxT( "Image Decoded Data : (%i) %i bytes" ), CoverDecData.GetBufSize(), CoverDecData.GetDataLen() );
//wxFileOutputStream FOut( wxT( "/home/jrios/test.jpg" ) );
//FOut.Write( CoverDecData.GetData(), CoverDecData.GetDataLen() );
//FOut.Close();
wxMemoryInputStream ImgInputStream( CoverDecData.GetData(), CoverDecData.GetDataLen() );
wxImage * CoverImage = new wxImage( ImgInputStream, CoverMime );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool SetXiphCommentCoverArt( Ogg::XiphComment * xiphcomment, const wxImage * image )
{
if( xiphcomment )
{
if( xiphcomment->contains( "COVERART" ) )
{
xiphcomment->removeField( "COVERARTMIME" );
xiphcomment->removeField( "COVERART" );
}
if( image )
{
wxMemoryOutputStream ImgOutputStream;
if( image->SaveFile( ImgOutputStream, wxBITMAP_TYPE_JPEG ) )
{
//ByteVector ImgData( ( TagLib::uint ) ImgOutputStream.GetSize() );
//ImgOutputStream.CopyTo( ImgData.data(), ImgOutputStream.GetSize() );
char * ImgData = ( char * ) malloc( ImgOutputStream.GetSize() );
if( ImgData )
{
ImgOutputStream.CopyTo( ImgData, ImgOutputStream.GetSize() );
xiphcomment->addField( "COVERARTMIME", "image/jpeg" );
xiphcomment->addField( "COVERART", wxStringToTString( wxBase64Encode( ImgData, ImgOutputStream.GetSize() ) ) );
free( ImgData );
return true;
}
else
{
guLogMessage( wxT( "Couldnt allocate memory saving the image to ogg" ) );
}
}
return false;
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
wxString GetXiphCommentLyrics( Ogg::XiphComment * xiphcomment )
{
if( xiphcomment && xiphcomment->contains( "LYRICS" ) )
{
return TStringTowxString( xiphcomment->fieldListMap()[ "LYRICS" ].front() );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool SetXiphCommentLyrics( Ogg::XiphComment * xiphcomment, const wxString &lyrics )
{
if( xiphcomment )
{
while( xiphcomment->contains( "LYRICS" ) )
{
xiphcomment->removeField( "LYRICS" );
}
if( !lyrics.IsEmpty() )
{
xiphcomment->addField( "LYRICS", wxStringToTString( lyrics ) );
}
return true;
}
return false;
}
#ifdef TAGLIB_WITH_MP4_COVERS
// -------------------------------------------------------------------------------- //
wxImage * GetMp4Image( TagLib::MP4::Tag * mp4tag )
{
if( mp4tag && mp4tag->itemListMap().contains( "covr" ) )
{
TagLib::MP4::CoverArtList Covers = mp4tag->itemListMap()[ "covr" ].toCoverArtList();
for( TagLib::MP4::CoverArtList::Iterator it = Covers.begin(); it != Covers.end(); it++ )
{
wxBitmapType ImgType = wxBITMAP_TYPE_INVALID;
if( it->format() == TagLib::MP4::CoverArt::PNG )
{
ImgType = wxBITMAP_TYPE_PNG;
}
else if( it->format() == TagLib::MP4::CoverArt::JPEG )
{
ImgType = wxBITMAP_TYPE_JPEG;
}
wxMemoryOutputStream ImgOutStream;
ImgOutStream.Write( it->data().data(), it->data().size() );
wxMemoryInputStream ImgInputStream( ImgOutStream );
wxImage * CoverImage = new wxImage( ImgInputStream, ImgType );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool SetMp4Image( TagLib::MP4::Tag * mp4tag, const wxImage * image )
{
if( mp4tag )
{
if( mp4tag->itemListMap().contains( "covr" ) )
{
mp4tag->itemListMap().erase( "covr" );
}
if( image )
{
wxMemoryOutputStream ImgOutputStream;
if( image && image->SaveFile( ImgOutputStream, wxBITMAP_TYPE_JPEG ) )
{
ByteVector ImgData( ( TagLib::uint ) ImgOutputStream.GetSize() );
ImgOutputStream.CopyTo( ImgData.data(), ImgOutputStream.GetSize() );
TagLib::MP4::CoverArtList CoverList;
TagLib::MP4::CoverArt Cover( TagLib::MP4::CoverArt::JPEG, ImgData );
CoverList.append( Cover );
mp4tag->itemListMap()[ "covr" ] = CoverList;
return true;
}
return false;
}
return true;
}
return false;
}
#endif
// -------------------------------------------------------------------------------- //
wxString GetMp4Lyrics( TagLib::MP4::Tag * mp4tag )
{
if( mp4tag )
{
if( mp4tag->itemListMap().contains( "\xa9lyr" ) )
return TStringTowxString( mp4tag->itemListMap()[ "\xa9lyr" ].toStringList().front() );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool SetMp4Lyrics( TagLib::MP4::Tag * mp4tag, const wxString &lyrics )
{
if( mp4tag )
{
if( mp4tag->itemListMap().contains( "\xa9lyr" ) )
{
mp4tag->itemListMap().erase( "\xa9lyr" );
}
if( !lyrics.IsEmpty() )
{
const TagLib::String Lyrics = wxStringToTString( lyrics );
mp4tag->itemListMap()[ "\xa9lyr" ] = TagLib::StringList( Lyrics );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
wxImage * GetApeItemImage( const TagLib::APE::Item &item )
{
if( item.type() == TagLib::APE::Item::Binary )
{
TagLib::ByteVector CoverData = item.value();
if( CoverData.size() )
{
wxMemoryOutputStream ImgOutStream;
ImgOutStream.Write( CoverData.data(), CoverData.size() );
wxMemoryInputStream ImgInputStream( ImgOutStream );
wxImage * CoverImage = new wxImage( ImgInputStream, wxBITMAP_TYPE_JPEG );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
wxImage * GetApeImage( TagLib::APE::Tag * apetag )
{
if( apetag )
{
if( apetag->itemListMap().contains( "Cover Art (front)" ) )
{
return GetApeItemImage( apetag->itemListMap()[ "Cover Art (front)" ] );
}
else if( apetag->itemListMap().contains( "Cover Art (other)" ) )
{
return GetApeItemImage( apetag->itemListMap()[ "Cover Art (other)" ] );
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool SetApeImage( TagLib::APE::Tag * apetag, const wxImage * image )
{
return false;
}
// -------------------------------------------------------------------------------- //
wxString GetApeLyrics( APE::Tag * apetag )
{
if( apetag )
{
if( apetag->itemListMap().contains( "LYRICS" ) )
{
return TStringTowxString( apetag->itemListMap()[ "LYRICS" ].toStringList().front() );
}
else if( apetag->itemListMap().contains( "UNSYNCED LYRICS" ) )
{
return TStringTowxString( apetag->itemListMap()[ "UNSYNCED LYRICS" ].toStringList().front() );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool SetApeLyrics( APE::Tag * apetag, const wxString &lyrics )
{
if( apetag )
{
if( apetag->itemListMap().contains( "LYRICS" ) )
{
apetag->removeItem( "LYRICS" );
}
if( apetag->itemListMap().contains( "UNSYNCED LYRICS" ) )
{
apetag->removeItem( "UNSYNCED LYRICS" );
}
if( !lyrics.IsEmpty() )
{
const TagLib::String Lyrics = wxStringToTString( lyrics );
apetag->addValue( "Lyrics", Lyrics );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
wxImage * GetASFImage( ASF::Tag * asftag )
{
if( asftag )
{
if( asftag->attributeListMap().contains( "WM/Picture" ) )
{
ByteVector PictureData = asftag->attributeListMap()[ "WM/Picture" ].front().toByteVector();
TagLib::ID3v2::AttachedPictureFrame * PicFrame;
PicFrame = ( TagLib::ID3v2::AttachedPictureFrame * ) PictureData.data();
int ImgDataSize = PicFrame->picture().size();
if( ImgDataSize > 0 )
{
//guLogMessage( wxT( "ASF header contains APIC frame with %u bytes." ), ImgDataSize );
wxMemoryOutputStream ImgOutStream;
ImgOutStream.Write( PicFrame->picture().data(), ImgDataSize );
wxMemoryInputStream ImgInputStream( ImgOutStream );
wxString ImgHandler = wxString( PicFrame->mimeType().toCString( true ), wxConvUTF8 );
ImgHandler.Replace( wxT( "/jpg" ), wxT( "/jpeg" ) );
wxImage * CoverImage = new wxImage( ImgInputStream, ImgHandler );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool SetASFImage( ASF::Tag * asftag, const wxImage * image )
{
return NULL;
}
// -------------------------------------------------------------------------------- //
// guTagInfo
// -------------------------------------------------------------------------------- //
guTagInfo::guTagInfo( const wxString &filename )
{
m_TagFile = NULL;
m_Tag = NULL;
SetFileName( filename );
m_Track = 0;
m_Year = 0;
m_Length = 0;
m_Bitrate = 0;
m_Rating = wxNOT_FOUND;
m_PlayCount = 0;
m_Compilation = false;
}
// -------------------------------------------------------------------------------- //
guTagInfo::~guTagInfo()
{
if( m_TagFile )
delete m_TagFile;
}
// -------------------------------------------------------------------------------- //
void guTagInfo::SetFileName( const wxString &filename )
{
m_FileName = filename;
if( !filename.IsEmpty() )
{
m_TagFile = new TagLib::FileRef( filename.mb_str( wxConvFile ), true, TagLib::AudioProperties::Fast );
}
if( m_TagFile && !m_TagFile->isNull() )
{
m_Tag = m_TagFile->tag();
if( !m_Tag )
{
guLogWarning( wxT( "Cant get tag object from '%s'" ), filename.c_str() );
}
}
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::Read( void )
{
AudioProperties * apro;
if( m_Tag )
{
m_TrackName = TStringTowxString( m_Tag->title() );
m_ArtistName = TStringTowxString( m_Tag->artist() );
m_AlbumName = TStringTowxString( m_Tag->album() );
m_GenreName = TStringTowxString( m_Tag->genre() );
m_Comments = TStringTowxString( m_Tag->comment() );
m_Track = m_Tag->track();
m_Year = m_Tag->year();
}
if( m_TagFile && m_Tag && ( apro = m_TagFile->audioProperties() ) )
{
m_Length = apro->length() * 1000;
m_Bitrate = apro->bitrate();
//m_Samplerate = apro->sampleRate();
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::Write( const int changedflag )
{
if( m_Tag && ( changedflag & guTRACK_CHANGED_DATA_TAGS ) )
{
m_Tag->setTitle( wxStringToTString( m_TrackName ) );
m_Tag->setArtist( wxStringToTString( m_ArtistName ) );
m_Tag->setAlbum( wxStringToTString( m_AlbumName ) );
m_Tag->setGenre( wxStringToTString( m_GenreName ) );
m_Tag->setComment( wxStringToTString( m_Comments ) );
m_Tag->setTrack( m_Track ); // set the id3v1 track
m_Tag->setYear( m_Year );
}
if( !m_TagFile->save() )
{
guLogWarning( wxT( "Tags Save failed for file '%s'" ), m_FileName.c_str() );
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::CanHandleImages( void )
{
return false;
}
// -------------------------------------------------------------------------------- //
wxImage * guTagInfo::GetImage( void )
{
return NULL;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::SetImage( const wxImage * image )
{
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::CanHandleLyrics( void )
{
return false;
}
// -------------------------------------------------------------------------------- //
wxString guTagInfo::GetLyrics( void )
{
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::SetLyrics( const wxString &lyrics )
{
return false;
}
// -------------------------------------------------------------------------------- //
void ID3v2_CheckLabelFrame( ID3v2::Tag * tagv2, const char * description, const wxString &value )
{
ID3v2::UserTextIdentificationFrame * frame;
//guLogMessage( wxT( "USERTEXT[ '%s' ] = '%s'" ), wxString( description, wxConvUTF8 ).c_str(), value.c_str() );
frame = ID3v2::UserTextIdentificationFrame::find( tagv2, description );
if( !frame )
{
frame = new ID3v2::UserTextIdentificationFrame( TagLib::String::UTF8 );
tagv2->addFrame( frame );
//frame->setDescription( TagLib::String( description, TagLib::String::UTF8 ) );
frame->setDescription( description );
}
if( frame )
{
frame->setText( wxStringToTString( value ) );
}
}
// -------------------------------------------------------------------------------- //
void Xiph_CheckLabelFrame( Ogg::XiphComment * xiphcomment, const char * description, const wxString &value )
{
//guLogMessage( wxT( "USERTEXT[ %s ] = '%s'" ), wxString( description, wxConvISO8859_1 ).c_str(), value.c_str() );
if( xiphcomment->fieldListMap().contains( description ) )
{
if( !value.IsEmpty() )
{
xiphcomment->addField( description, wxStringToTString( value ) );
}
else
{
xiphcomment->removeField( description );
}
}
else
{
if( !value.IsEmpty() )
{
xiphcomment->addField( description, wxStringToTString( value ) );
}
}
}
// -------------------------------------------------------------------------------- //
bool guStrDiskToDiskNum( const wxString &diskstr, int &disknum, int &disktotal )
{
unsigned long Number;
disknum = 0;
disktotal = 0;
wxString DiskNum = diskstr.BeforeFirst( wxT( '/' ) );
if( !DiskNum.IsEmpty() )
{
if( DiskNum.ToULong( &Number ) )
{
disknum = Number;
if( diskstr.Find( wxT( "/" ) ) )
{
DiskNum = diskstr.AfterFirst( wxT( '/' ) );
if( DiskNum.ToULong( &Number ) )
{
disktotal = Number;
}
}
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void Mp4_CheckLabelFrame( TagLib::MP4::Tag * mp4tag, const char * description, const wxString &value )
{
//guLogMessage( wxT( "USERTEXT[ %s ] = '%s'" ), wxString( description, wxConvISO8859_1 ).c_str(), value.c_str() );
if( mp4tag->itemListMap().contains( description ) )
{
if( !value.IsEmpty() )
{
mp4tag->itemListMap()[ description ] = TagLib::MP4::Item( TagLib::StringList( wxStringToTString( value ) ) );
}
else
{
mp4tag->itemListMap().erase( description );
}
}
else
{
if( !value.IsEmpty() )
{
mp4tag->itemListMap().insert( description, TagLib::MP4::Item( TagLib::StringList( wxStringToTString( value ) ) ) );
}
}
}
// -------------------------------------------------------------------------------- //
void Ape_CheckLabelFrame( TagLib::APE::Tag * apetag, const char * description, const wxString &value )
{
//guLogMessage( wxT( "USERTEXT[ %s ] = '%s'" ), wxString( description, wxConvISO8859_1 ).c_str(), value.c_str() );
if( apetag->itemListMap().contains( description ) )
apetag->removeItem( description );
if( !value.IsEmpty() )
{
apetag->addValue( description, wxStringToTString( value ) );
}
}
// -------------------------------------------------------------------------------- //
void ASF_CheckLabelFrame( ASF::Tag * asftag, const char * description, const wxString &value )
{
//guLogMessage( wxT( "USERTEXT[ %s ] = '%s'" ), wxString( description, wxConvISO8859_1 ).c_str(), value.c_str() );
if( asftag->attributeListMap().contains( description ) )
asftag->removeItem( description );
if( !value.IsEmpty() )
{
asftag->setAttribute( description, wxStringToTString( value ) );
}
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::ReadExtendedTags( ID3v2::Tag * tag )
{
if( tag )
{
if( tag->frameListMap().contains( "TPOS" ) )
{
m_Disk = TStringTowxString( tag->frameListMap()[ "TPOS" ].front()->toString() );
}
if( tag->frameListMap().contains( "TCOM" ) )
{
m_Composer = TStringTowxString( tag->frameListMap()[ "TCOM" ].front()->toString() );
}
if( tag->frameListMap().contains( "TPE2" ) )
{
m_AlbumArtist = TStringTowxString( tag->frameListMap()[ "TPE2" ].front()->toString() );
}
if( tag->frameListMap().contains( "TCMP" ) )
{
m_Compilation = TStringTowxString( tag->frameListMap()[ "TCMP" ].front()->toString() ) == wxT( "1" );
}
TagLib::ID3v2::PopularimeterFrame * PopMFrame = NULL;
PopMFrame = GetPopM( tag, "Guayadeque" );
if( !PopMFrame )
PopMFrame = GetPopM( tag, "" );
if( PopMFrame )
{
m_Rating = guPopMToRating( PopMFrame->rating() );
m_PlayCount = PopMFrame->counter();
}
if( m_TrackLabels.Count() == 0 )
{
ID3v2::UserTextIdentificationFrame * Frame = ID3v2::UserTextIdentificationFrame::find( tag, "TRACK_LABELS" );
if( !Frame )
Frame = ID3v2::UserTextIdentificationFrame::find( tag, "guTRLABELS" );
if( Frame )
{
//guLogMessage( wxT( "*Track Label: '%s'" ), TStringTowxString( Frame->fieldList()[ 1 ] ).c_str() );
// [guTRLABELS] guTRLABELS labels
StringList TrLabelsList = Frame->fieldList();
if( TrLabelsList.size() )
{
m_TrackLabelsStr = TStringTowxString( TrLabelsList[ 1 ] );
m_TrackLabels = wxStringTokenize( m_TrackLabelsStr, wxT( "|" ) );
}
}
}
if( m_ArtistLabels.Count() == 0 )
{
ID3v2::UserTextIdentificationFrame * Frame = ID3v2::UserTextIdentificationFrame::find( tag, "ARTIST_LABELS" );
if( !Frame )
Frame = ID3v2::UserTextIdentificationFrame::find( tag, "guARLABELS" );
if( Frame )
{
//guLogMessage( wxT( "*Artist Label: '%s'" ), TStringTowxString( Frame->fieldList()[ 1 ] ).c_str() );
StringList ArLabelsList = Frame->fieldList();
if( ArLabelsList.size() )
{
m_ArtistLabelsStr = TStringTowxString( ArLabelsList[ 1 ] );
m_ArtistLabels = wxStringTokenize( m_ArtistLabelsStr, wxT( "|" ) );
}
}
}
if( m_AlbumLabels.Count() == 0 )
{
ID3v2::UserTextIdentificationFrame * Frame = ID3v2::UserTextIdentificationFrame::find( tag, "ALBUM_LABELS" );
if( !Frame )
Frame = ID3v2::UserTextIdentificationFrame::find( tag, "guALLABELS" );
if( Frame )
{
//guLogMessage( wxT( "*Album Label: '%s'" ), TStringTowxString( Frame->fieldList()[ 1 ] ).c_str() );
StringList AlLabelsList = Frame->fieldList();
if( AlLabelsList.size() )
{
m_AlbumLabelsStr = TStringTowxString( AlLabelsList[ 1 ] );
m_AlbumLabels = wxStringTokenize( m_AlbumLabelsStr, wxT( "|" ) );
}
}
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::WriteExtendedTags( ID3v2::Tag * tag, const int changedflag )
{
if( tag )
{
if( changedflag & guTRACK_CHANGED_DATA_TAGS )
{
TagLib::ID3v2::TextIdentificationFrame * frame;
tag->removeFrames( "TPOS" );
frame = new TagLib::ID3v2::TextIdentificationFrame( "TPOS" );
frame->setText( wxStringToTString( m_Disk ) );
tag->addFrame( frame );
tag->removeFrames( "TCOM" );
frame = new TagLib::ID3v2::TextIdentificationFrame( "TCOM" );
frame->setText( wxStringToTString( m_Composer ) );
tag->addFrame( frame );
tag->removeFrames( "TPE2" );
frame = new TagLib::ID3v2::TextIdentificationFrame( "TPE2" );
frame->setText( wxStringToTString( m_AlbumArtist ) );
tag->addFrame( frame );
//tag->removeFrames( "TCMP" );
//frame = new TagLib::ID3v2::TextIdentificationFrame( "TCMP" );
//frame->setText( wxStringToTString( wxString::Format( wxT( "%u" ), m_Compilation ) ) );
//tag->addFrame( frame );
// I have found several TRCK fields in the mp3s
tag->removeFrames( "TRCK" );
tag->setTrack( m_Track );
}
if( changedflag & guTRACK_CHANGED_DATA_RATING )
{
guLogMessage( wxT( "Writing ratings and playcount..." ) );
TagLib::ID3v2::PopularimeterFrame * PopMFrame = GetPopM( tag, "Guayadeque" );
if( !PopMFrame )
{
PopMFrame = new TagLib::ID3v2::PopularimeterFrame();
tag->addFrame( PopMFrame );
PopMFrame->setEmail( "Guayadeque" );
}
PopMFrame->setRating( guRatingToPopM( m_Rating ) );
PopMFrame->setCounter( m_PlayCount );
}
if( changedflag & guTRACK_CHANGED_DATA_LABELS )
{
// The Labels
ID3v2_CheckLabelFrame( tag, "ARTIST_LABELS", m_ArtistLabelsStr );
ID3v2_CheckLabelFrame( tag, "ALBUM_LABELS", m_AlbumLabelsStr );
ID3v2_CheckLabelFrame( tag, "TRACK_LABELS", m_TrackLabelsStr );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::ReadExtendedTags( Ogg::XiphComment * tag )
{
if( tag )
{
if( tag->fieldListMap().contains( "COMPOSER" ) )
{
m_Composer = TStringTowxString( tag->fieldListMap()["COMPOSER"].front() );
}
if( tag->fieldListMap().contains( "DISCNUMBER" ) )
{
m_Disk = TStringTowxString( tag->fieldListMap()["DISCNUMBER"].front() );
}
if( tag->fieldListMap().contains( "COMPILATION" ) )
{
m_Compilation = TStringTowxString( tag->fieldListMap()["COMPILATION"].front() ) == wxT( "1" );
}
if( tag->fieldListMap().contains( "ALBUMARTIST" ) )
{
m_AlbumArtist = TStringTowxString( tag->fieldListMap()["ALBUMARTIST"].front() );
}
else if( tag->fieldListMap().contains( "ALBUM ARTIST" ) )
{
m_AlbumArtist = TStringTowxString( tag->fieldListMap()["ALBUM ARTIST"].front() );
}
// Rating
if( tag->fieldListMap().contains( "RATING" ) )
{
long Rating = 0;
if( TStringTowxString( tag->fieldListMap()["RATING"].front() ).ToLong( &Rating ) )
{
if( Rating )
{
if( Rating > 5 )
{
m_Rating = guPopMToRating( Rating );
}
else
{
m_Rating = Rating;
}
}
}
}
if( tag->fieldListMap().contains( "PLAY_COUNTER" ) )
{
long PlayCount = 0;
if( TStringTowxString( tag->fieldListMap()["PLAY_COUNTER"].front() ).ToLong( &PlayCount ) )
{
m_PlayCount = PlayCount;
}
}
// Labels
if( m_TrackLabels.Count() == 0 )
{
if( tag->fieldListMap().contains( "TRACK_LABELS" ) )
{
m_TrackLabelsStr = TStringTowxString( tag->fieldListMap()["TRACK_LABELS"].front() );
//guLogMessage( wxT( "*Track Label: '%s'\n" ), m_TrackLabelsStr.c_str() );
m_TrackLabels = wxStringTokenize( m_TrackLabelsStr, wxT( "|" ) );
}
}
if( m_ArtistLabels.Count() == 0 )
{
if( tag->fieldListMap().contains( "ARTIST_LABELS" ) )
{
m_ArtistLabelsStr = TStringTowxString( tag->fieldListMap()["ARTIST_LABELS"].front() );
//guLogMessage( wxT( "*Artist Label: '%s'\n" ), m_ArtistLabelsStr.c_str() );
m_ArtistLabels = wxStringTokenize( m_ArtistLabelsStr, wxT( "|" ) );
}
}
if( m_AlbumLabels.Count() == 0 )
{
if( tag->fieldListMap().contains( "ALBUM_LABELS" ) )
{
m_AlbumLabelsStr = TStringTowxString( tag->fieldListMap()["ALBUM_LABELS"].front() );
//guLogMessage( wxT( "*Album Label: '%s'\n" ), m_AlbumLabelsStr.c_str() );
m_AlbumLabels = wxStringTokenize( m_AlbumLabelsStr, wxT( "|" ) );
}
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::WriteExtendedTags( Ogg::XiphComment * tag, const int changedflag )
{
if( tag )
{
if( changedflag & guTRACK_CHANGED_DATA_TAGS )
{
tag->addField( "DISCNUMBER", wxStringToTString( m_Disk ) );
tag->addField( "COMPOSER", wxStringToTString( m_Composer ) );
tag->addField( "COMPILATION", wxStringToTString( wxString::Format( wxT( "%u" ), m_Compilation ) ) );
tag->addField( "ALBUMARTIST", wxStringToTString( m_AlbumArtist ) );
}
if( changedflag & guTRACK_CHANGED_DATA_RATING )
{
tag->addField( "RATING", wxStringToTString( wxString::Format( wxT( "%u" ), guRatingToPopM( m_Rating ) ) ) );
tag->addField( "PLAY_COUNTER", wxStringToTString( wxString::Format( wxT( "%u" ), m_PlayCount ) ) );
}
if( changedflag & guTRACK_CHANGED_DATA_LABELS )
{
// The Labels
Xiph_CheckLabelFrame( tag, "ARTIST_LABELS", m_ArtistLabelsStr );
Xiph_CheckLabelFrame( tag, "ALBUM_LABELS", m_AlbumLabelsStr );
Xiph_CheckLabelFrame( tag, "TRACK_LABELS", m_TrackLabelsStr );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::ReadExtendedTags( MP4::Tag * tag )
{
if( tag )
{
if( tag->itemListMap().contains( "aART" ) )
{
m_AlbumArtist = TStringTowxString( tag->itemListMap()["aART"].toStringList().front() );
}
if( tag->itemListMap().contains( "\xA9wrt" ) )
{
m_Composer = TStringTowxString( tag->itemListMap()["\xa9wrt"].toStringList().front() );
}
if( tag->itemListMap().contains( "disk" ) )
{
m_Disk = wxString::Format( wxT( "%i/%i" ),
tag->itemListMap()["disk"].toIntPair().first,
tag->itemListMap()["disk"].toIntPair().second );
}
if( tag->itemListMap().contains( "cpil" ) )
{
m_Compilation = tag->itemListMap()["cpil"].toBool();
}
// Rating
if( tag->itemListMap().contains( "----:com.apple.iTunes:RATING" ) )
{
long Rating = 0;
if( TStringTowxString( tag->itemListMap()["----:com.apple.iTunes:RATING"].toStringList().front() ).ToLong( &Rating ) )
{
if( Rating )
{
if( Rating > 5 )
{
m_Rating = guPopMToRating( Rating );
}
else
{
m_Rating = Rating;
}
}
}
}
if( tag->itemListMap().contains( "----:com.apple.iTunes:PLAY_COUNTER" ) )
{
long PlayCount = 0;
if( TStringTowxString( tag->itemListMap()["----:com.apple.iTunes:PLAY_COUNTER"].toStringList().front() ).ToLong( &PlayCount ) )
{
m_PlayCount = PlayCount;
}
}
// Labels
if( m_TrackLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "----:com.apple.iTunes:TRACK_LABELS" ) )
{
m_TrackLabelsStr = TStringTowxString( tag->itemListMap()["----:com.apple.iTunes:TRACK_LABELS"].toStringList().front() );
m_TrackLabels = wxStringTokenize( m_TrackLabelsStr, wxT( "|" ) );
}
}
if( m_ArtistLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "----:com.apple.iTunes:ARTIST_LABELS" ) )
{
m_ArtistLabelsStr = TStringTowxString( tag->itemListMap()["----:com.apple.iTunes:ARTIST_LABELS"].toStringList().front() );
m_ArtistLabels = wxStringTokenize( m_ArtistLabelsStr, wxT( "|" ) );
}
}
if( m_AlbumLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "----:com.apple.iTunes:ALBUM_LABELS" ) )
{
m_AlbumLabelsStr = TStringTowxString( tag->itemListMap()["----:com.apple.iTunes:ALBUM_LABELS"].toStringList().front() );
m_AlbumLabels = wxStringTokenize( m_AlbumLabelsStr, wxT( "|" ) );
}
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::WriteExtendedTags( MP4::Tag * tag, const int changedflag )
{
if( tag )
{
if( changedflag & guTRACK_CHANGED_DATA_TAGS )
{
tag->itemListMap()["aART"] = TagLib::StringList( wxStringToTString( m_AlbumArtist ) );
tag->itemListMap()["\xA9wrt"] = TagLib::StringList( wxStringToTString( m_Composer ) );
int first;
int second;
guStrDiskToDiskNum( m_Disk, first, second );
tag->itemListMap()["disk"] = TagLib::MP4::Item( first, second );
tag->itemListMap()["cpil"] = TagLib::MP4::Item( m_Compilation );
}
if( changedflag & guTRACK_CHANGED_DATA_RATING )
{
tag->itemListMap()["----:com.apple.iTunes:RATING" ] = TagLib::MP4::Item( wxStringToTString( wxString::Format( wxT( "%u" ), guRatingToPopM( m_Rating ) ) ) );
tag->itemListMap()[ "----:com.apple.iTunes:PLAY_COUNTER" ] = TagLib::MP4::Item( wxStringToTString( wxString::Format( wxT( "%u" ), m_PlayCount ) ) );
}
if( changedflag & guTRACK_CHANGED_DATA_LABELS )
{
// The Labels
Mp4_CheckLabelFrame( tag, "----:com.apple.iTunes:ARTIST_LABELS", m_ArtistLabelsStr );
Mp4_CheckLabelFrame( tag, "----:com.apple.iTunes:ALBUM_LABELS", m_AlbumLabelsStr );
Mp4_CheckLabelFrame( tag, "----:com.apple.iTunes:TRACK_LABELS", m_TrackLabelsStr );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::ReadExtendedTags( APE::Tag * tag )
{
if( tag )
{
if( tag->itemListMap().contains( "COMPOSER" ) )
{
m_Composer = TStringTowxString( tag->itemListMap()["COMPOSER"].toStringList().front() );
}
if( tag->itemListMap().contains( "DISCNUMBER" ) )
{
m_Disk = TStringTowxString( tag->itemListMap()["DISCNUMBER"].toStringList().front() );
}
if( tag->itemListMap().contains( "COMPILATION" ) )
{
m_Compilation = TStringTowxString( tag->itemListMap()["COMPILATION"].toStringList().front() ) == wxT( "1" );
}
if( tag->itemListMap().contains( "ALBUM ARTIST" ) )
{
m_AlbumArtist = TStringTowxString( tag->itemListMap()["ALBUM ARTIST"].toStringList().front() );
}
else if( tag->itemListMap().contains( "ALBUMARTIST" ) )
{
m_AlbumArtist = TStringTowxString( tag->itemListMap()["ALBUMARTIST"].toStringList().front() );
}
// Rating
if( tag->itemListMap().contains( "RATING" ) )
{
long Rating = 0;
if( TStringTowxString( tag->itemListMap()["RATING"].toStringList().front() ).ToLong( &Rating ) )
{
if( Rating )
{
if( Rating > 5 )
{
m_Rating = guPopMToRating( Rating );
}
else
{
m_Rating = Rating;
}
}
}
}
if( tag->itemListMap().contains( "PLAY_COUNTER" ) )
{
long PlayCount = 0;
if( TStringTowxString( tag->itemListMap()["PLAY_COUNTER"].toStringList().front() ).ToLong( &PlayCount ) )
{
m_PlayCount = PlayCount;
}
}
// Labels
if( m_TrackLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "TRACK_LABELS" ) )
{
m_TrackLabelsStr = TStringTowxString( tag->itemListMap()["TRACK_LABELS"].toStringList().front() );
//guLogMessage( wxT( "*Track Label: '%s'\n" ), m_TrackLabelsStr.c_str() );
m_TrackLabels = wxStringTokenize( m_TrackLabelsStr, wxT( "|" ) );
}
}
if( m_ArtistLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "ARTIST_LABELS" ) )
{
m_ArtistLabelsStr = TStringTowxString( tag->itemListMap()["ARTIST_LABELS"].toStringList().front() );
//guLogMessage( wxT( "*Artist Label: '%s'\n" ), m_ArtistLabelsStr.c_str() );
m_ArtistLabels = wxStringTokenize( m_ArtistLabelsStr, wxT( "|" ) );
}
}
if( m_AlbumLabels.Count() == 0 )
{
if( tag->itemListMap().contains( "ALBUM_LABELS" ) )
{
m_AlbumLabelsStr = TStringTowxString( tag->itemListMap()["ALBUM_LABELS"].toStringList().front() );
//guLogMessage( wxT( "*Album Label: '%s'\n" ), m_AlbumLabelsStr.c_str() );
m_AlbumLabels = wxStringTokenize( m_AlbumLabelsStr, wxT( "|" ) );
}
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::WriteExtendedTags( APE::Tag * tag, const int changedflag )
{
if( tag )
{
if( changedflag & guTRACK_CHANGED_DATA_TAGS )
{
tag->addValue( "COMPOSER", wxStringToTString( m_Composer ) );
tag->addValue( "DISCNUMBER", wxStringToTString( m_Disk ) );
tag->addValue( "COMPILATION", wxStringToTString( wxString::Format( wxT( "%u" ), m_Compilation ) ) );
tag->addValue( "ALBUM ARTIST", wxStringToTString( m_AlbumArtist ) );
}
if( changedflag & guTRACK_CHANGED_DATA_RATING )
{
tag->addValue( "RATING", wxStringToTString( wxString::Format( wxT( "%u" ), guRatingToPopM( m_Rating ) ) ) );
tag->addValue( "PLAY_COUNTER", wxStringToTString( wxString::Format( wxT( "%u" ), m_PlayCount ) ) );
}
if( changedflag & guTRACK_CHANGED_DATA_LABELS )
{
// The Labels
Ape_CheckLabelFrame( tag, "ARTIST_LABELS", m_ArtistLabelsStr );
Ape_CheckLabelFrame( tag, "ALBUM_LABELS", m_AlbumLabelsStr );
Ape_CheckLabelFrame( tag, "TRACK_LABELS", m_TrackLabelsStr );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::ReadExtendedTags( ASF::Tag * tag )
{
if( tag )
{
if( tag->attributeListMap().contains( "WM/PartOfSet" ) )
{
m_Disk = TStringTowxString( tag->attributeListMap()[ "WM/PartOfSet" ].front().toString() );
}
if( tag->attributeListMap().contains( "WM/Composer" ) )
{
m_Composer = TStringTowxString( tag->attributeListMap()[ "WM/Composer" ].front().toString() );
}
if( tag->attributeListMap().contains( "WM/AlbumArtist" ) )
{
m_AlbumArtist = TStringTowxString( tag->attributeListMap()[ "WM/AlbumArtist" ].front().toString() );
}
long Rating = 0;
if( tag->attributeListMap().contains( "WM/SharedUserRating" ) )
{
TStringTowxString( tag->attributeListMap()[ "WM/SharedUserRating" ].front().toString() ).ToLong( &Rating );
}
if( !Rating && tag->attributeListMap().contains( "Rating" ) )
{
TStringTowxString( tag->attributeListMap()[ "Rating" ].front().toString() ).ToLong( &Rating );
}
if( Rating )
{
if( Rating > 5 )
{
m_Rating = guWMRatingToRating( Rating );
}
else
{
m_Rating = Rating;
}
}
if( m_TrackLabels.Count() == 0 )
{
if( tag->attributeListMap().contains( "TRACK_LABELS" ) )
{
m_TrackLabelsStr = TStringTowxString( tag->attributeListMap()[ "TRACK_LABELS" ].front().toString() );
m_TrackLabels = wxStringTokenize( m_TrackLabelsStr, wxT( "|" ) );
}
}
if( m_ArtistLabels.Count() == 0 )
{
if( tag->attributeListMap().contains( "ARTIST_LABELS" ) )
{
m_ArtistLabelsStr = TStringTowxString( tag->attributeListMap()[ "ARTIST_LABELS" ].front().toString() );
m_ArtistLabels = wxStringTokenize( m_ArtistLabelsStr, wxT( "|" ) );
}
}
if( m_AlbumLabels.Count() == 0 )
{
if( tag->attributeListMap().contains( "ALBUM_LABELS" ) )
{
m_AlbumLabelsStr = TStringTowxString( tag->attributeListMap()[ "ALBUM_LABELS" ].front().toString() );
m_AlbumLabels = wxStringTokenize( m_AlbumLabelsStr, wxT( "|" ) );
}
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTagInfo::WriteExtendedTags( ASF::Tag * tag, const int changedflag )
{
if( tag )
{
if( changedflag & guTRACK_CHANGED_DATA_TAGS )
{
tag->removeItem( "WM/PartOfSet" );
tag->setAttribute( "WM/PartOfSet", wxStringToTString( m_Disk ) );
tag->removeItem( "WM/Composer" );
tag->setAttribute( "WM/Composer", wxStringToTString( m_Composer ) );
tag->removeItem( "WM/AlbumArtist" );
tag->setAttribute( "WM/AlbumArtist", wxStringToTString( m_AlbumArtist ) );
}
if( changedflag & guTRACK_CHANGED_DATA_RATING )
{
tag->removeItem( "WM/SharedUserRating" );
int WMRatings[] = { 0, 0, 1, 25, 50, 75, 99 };
tag->setAttribute( "WM/SharedUserRating", wxStringToTString( wxString::Format( wxT( "%i" ), WMRatings[ m_Rating + 1 ] ) ) );
}
if( changedflag & guTRACK_CHANGED_DATA_LABELS )
{
// The Labels
ASF_CheckLabelFrame( tag, "ARTIST_LABELS", m_ArtistLabelsStr );
ASF_CheckLabelFrame( tag, "ALBUM_LABELS", m_AlbumLabelsStr );
ASF_CheckLabelFrame( tag, "TRACK_LABELS", m_TrackLabelsStr );
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
// guMp3TagInfo
// -------------------------------------------------------------------------------- //
guMp3TagInfo::guMp3TagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_TagId3v2 = ( ( TagLib::MPEG::File * ) m_TagFile->file() )->ID3v2Tag();
}
else
{
m_TagId3v2 = NULL;
}
}
// -------------------------------------------------------------------------------- //
guMp3TagInfo::~guMp3TagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::Read( void )
{
if( guTagInfo::Read() )
{
// If its a ID3v2 Tag try to load the labels
if( m_TagId3v2 )
{
ReadExtendedTags( m_TagId3v2 );
}
}
else
{
guLogError( wxT( "Could not read tags from file '%s'" ), m_FileName.c_str() );
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::Write( const int changedflag )
{
if( m_TagId3v2 )
{
WriteExtendedTags( m_TagId3v2, changedflag );
}
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guMp3TagInfo::GetImage( void )
{
if( m_TagId3v2 )
{
return GetID3v2Image( m_TagId3v2 );
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::SetImage( const wxImage * image )
{
if( m_TagId3v2 )
{
SetID3v2Image( m_TagId3v2, image );
}
else
return false;
return true;
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guMp3TagInfo::GetLyrics( void )
{
if( m_TagId3v2 )
{
return GetID3v2Lyrics( m_TagId3v2 );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guMp3TagInfo::SetLyrics( const wxString &lyrics )
{
if( m_TagId3v2 )
{
SetID3v2Lyrics( m_TagId3v2, lyrics );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
// guFlacTagInfo
// -------------------------------------------------------------------------------- //
guFlacTagInfo::guFlacTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_XiphComment = ( ( TagLib::FLAC::File * ) m_TagFile->file() )->xiphComment();
}
else
m_XiphComment = NULL;
}
// -------------------------------------------------------------------------------- //
guFlacTagInfo::~guFlacTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_XiphComment );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_XiphComment, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * GetFlacImage( List<FLAC::Picture *> Pictures, TagLib::FLAC::Picture::Type imagetype )
{
wxImage * CoverImage = NULL;
for( List<FLAC::Picture *>::Iterator it = Pictures.begin(); it != Pictures.end(); ++it )
{
FLAC::Picture * Pic = ( * it );
if( Pic->type() == imagetype )
{
wxBitmapType ImgType = wxBITMAP_TYPE_INVALID;
if( Pic->mimeType() == "image/png" )
{
ImgType = wxBITMAP_TYPE_PNG;
}
else if( Pic->mimeType() == "image/jpeg" )
{
ImgType = wxBITMAP_TYPE_JPEG;
}
wxMemoryOutputStream ImgOutStream;
ImgOutStream.Write( Pic->data().data(), Pic->data().size() );
wxMemoryInputStream ImgInputStream( ImgOutStream );
wxImage * CoverImage = new wxImage( ImgInputStream, ImgType );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
}
}
}
}
return CoverImage;
}
// -------------------------------------------------------------------------------- //
wxImage * guFlacTagInfo::GetImage( void )
{
wxImage * CoverImage = NULL;
if( m_TagFile )
{
List<FLAC::Picture *> Pictures = ( ( FLAC::File * ) m_TagFile->file() )->pictureList();
if( Pictures.size() > 0 )
{
CoverImage = GetFlacImage( Pictures, TagLib::FLAC::Picture::FrontCover );
if( !CoverImage )
{
CoverImage = GetFlacImage( Pictures, TagLib::FLAC::Picture::Other );
}
}
}
return CoverImage;
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::SetImage( const wxImage * image )
{
bool RetVal = false;
if( m_TagFile )
{
FLAC::File * FlacFile = ( FLAC::File * ) m_TagFile->file();
FlacFile->removePictures();
if( image )
{
wxMemoryOutputStream ImgOutputStream;
if( image && image->SaveFile( ImgOutputStream, wxBITMAP_TYPE_JPEG ) )
{
ByteVector ImgData( ( TagLib::uint ) ImgOutputStream.GetSize() );
ImgOutputStream.CopyTo( ImgData.data(), ImgOutputStream.GetSize() );
FLAC::Picture * Pic = new FLAC::Picture();
if( Pic )
{
Pic->setData( ImgData );
//Pic->setDescription( "" );
Pic->setMimeType( "image/jpeg" );
Pic->setType( TagLib::FLAC::Picture::FrontCover );
FlacFile->addPicture( Pic );
return true;
}
}
return false;
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guFlacTagInfo::GetLyrics( void )
{
return GetXiphCommentLyrics( m_XiphComment );
}
// -------------------------------------------------------------------------------- //
bool guFlacTagInfo::SetLyrics( const wxString &lyrics )
{
return SetXiphCommentLyrics( m_XiphComment, lyrics );
}
// -------------------------------------------------------------------------------- //
// guOggTagInfo
// -------------------------------------------------------------------------------- //
guOggTagInfo::guOggTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_XiphComment = ( ( TagLib::Ogg::Vorbis::File * ) m_TagFile->file() )->tag();
}
else
m_XiphComment = NULL;
}
// -------------------------------------------------------------------------------- //
guOggTagInfo::~guOggTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_XiphComment );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_XiphComment, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guOggTagInfo::GetImage( void )
{
return GetXiphCommentCoverArt( m_XiphComment );
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::SetImage( const wxImage * image )
{
return SetXiphCommentCoverArt( m_XiphComment, image );
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guOggTagInfo::GetLyrics( void )
{
return GetXiphCommentLyrics( m_XiphComment );
}
// -------------------------------------------------------------------------------- //
bool guOggTagInfo::SetLyrics( const wxString &lyrics )
{
return SetXiphCommentLyrics( m_XiphComment, lyrics );
}
// -------------------------------------------------------------------------------- //
// guMp4TagInfo
// -------------------------------------------------------------------------------- //
guMp4TagInfo::guMp4TagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_Mp4Tag = ( ( TagLib::MP4::File * ) m_TagFile->file() )->tag();
}
else
m_Mp4Tag = NULL;
}
// -------------------------------------------------------------------------------- //
guMp4TagInfo::~guMp4TagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_Mp4Tag );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_Mp4Tag, changedflag );
return guTagInfo::Write( changedflag );
}
#ifdef TAGLIB_WITH_MP4_COVERS
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guMp4TagInfo::GetImage( void )
{
return GetMp4Image( m_Mp4Tag );
}
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::SetImage( const wxImage * image )
{
return SetMp4Image( m_Mp4Tag, image );
}
#endif
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guMp4TagInfo::GetLyrics( void )
{
if( m_TagFile )
{
TagLib::MP4::File * TagFile = ( TagLib::MP4::File * ) m_TagFile->file();
if( TagFile )
{
return GetMp4Lyrics( TagFile->tag() );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guMp4TagInfo::SetLyrics( const wxString &lyrics )
{
if( m_TagFile )
{
TagLib::MP4::File * TagFile = ( TagLib::MP4::File * ) m_TagFile->file();
if( TagFile )
{
return SetMp4Lyrics( TagFile->tag(), lyrics );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
// guMpcTagInfo
// -------------------------------------------------------------------------------- //
guMpcTagInfo::guMpcTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_ApeTag = ( ( TagLib::MPC::File * ) m_TagFile->file() )->APETag();
}
else
m_ApeTag = NULL;
}
// -------------------------------------------------------------------------------- //
guMpcTagInfo::~guMpcTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guMpcTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_ApeTag );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guMpcTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_ApeTag, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guMpcTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guMpcTagInfo::GetImage( void )
{
return GetApeImage( m_ApeTag );
}
// -------------------------------------------------------------------------------- //
bool guMpcTagInfo::SetImage( const wxImage * image )
{
//return m_ApeTag && SetApeImage( m_ApeTag, image ) && Write();
return m_ApeTag && SetApeImage( m_ApeTag, image );
}
// -------------------------------------------------------------------------------- //
// guWavPackTagInfo
// -------------------------------------------------------------------------------- //
guWavPackTagInfo::guWavPackTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_ApeTag = ( ( TagLib::WavPack::File * ) m_TagFile->file() )->APETag();
}
else
m_ApeTag = NULL;
}
// -------------------------------------------------------------------------------- //
guWavPackTagInfo::~guWavPackTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_ApeTag );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_ApeTag, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guWavPackTagInfo::GetImage( void )
{
return GetApeImage( m_ApeTag );
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::SetImage( const wxImage * image )
{
return m_ApeTag && SetApeImage( m_ApeTag, image );
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guWavPackTagInfo::GetLyrics( void )
{
return GetApeLyrics( m_ApeTag );
}
// -------------------------------------------------------------------------------- //
bool guWavPackTagInfo::SetLyrics( const wxString &lyrics )
{
return SetApeLyrics( m_ApeTag, lyrics );
}
#ifdef TAGLIB_WITH_APE_SUPPORT
// -------------------------------------------------------------------------------- //
// guApeTagInfo
// -------------------------------------------------------------------------------- //
guApeTagInfo::guApeTagInfo( const wxString &filename ) : guTagInfo( filename )
{
m_TagId3v1 = NULL;
m_ApeTag = NULL;
if( m_TagFile && !m_TagFile->isNull() )
{
m_TagId3v1 = ( ( TagLib::APE::File * ) m_TagFile->file() )->ID3v1Tag();
m_ApeTag = ( ( TagLib::APE::File * ) m_TagFile->file() )->APETag();
}
}
// -------------------------------------------------------------------------------- //
guApeTagInfo::~guApeTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guApeTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_ApeTag );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guApeTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_ApeTag, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guApeTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guApeTagInfo::GetLyrics( void )
{
return GetApeLyrics( m_ApeTag );
}
// -------------------------------------------------------------------------------- //
bool guApeTagInfo::SetLyrics( const wxString &lyrics )
{
return SetApeLyrics( m_ApeTag, lyrics );
}
#endif
// -------------------------------------------------------------------------------- //
// guTrueAudioTagInfo
// -------------------------------------------------------------------------------- //
guTrueAudioTagInfo::guTrueAudioTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_TagId3v2 = ( ( TagLib::TrueAudio::File * ) m_TagFile->file() )->ID3v2Tag();
}
else
{
m_TagId3v2 = NULL;
}
}
// -------------------------------------------------------------------------------- //
guTrueAudioTagInfo::~guTrueAudioTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
// If its a ID3v2 Tag try to load the labels
ReadExtendedTags( m_TagId3v2 );
return true;
}
else
{
guLogError( wxT( "Could not read tags from file '%s'" ), m_FileName.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_TagId3v2, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guTrueAudioTagInfo::GetImage( void )
{
if( m_TagId3v2 )
{
return GetID3v2Image( m_TagId3v2 );
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::SetImage( const wxImage * image )
{
if( m_TagId3v2 )
{
SetID3v2Image( m_TagId3v2, image );
}
else
return false;
return true;
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guTrueAudioTagInfo::GetLyrics( void )
{
if( m_TagId3v2 )
{
return GetID3v2Lyrics( m_TagId3v2 );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guTrueAudioTagInfo::SetLyrics( const wxString &lyrics )
{
if( m_TagId3v2 )
{
SetID3v2Lyrics( m_TagId3v2, lyrics );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
// guASFTagInfo
// -------------------------------------------------------------------------------- //
guASFTagInfo::guASFTagInfo( const wxString &filename ) : guTagInfo( filename )
{
if( m_TagFile && !m_TagFile->isNull() )
{
m_ASFTag = ( ( TagLib::ASF::File * ) m_TagFile->file() )->tag();
}
else
{
m_ASFTag = NULL;
}
}
// -------------------------------------------------------------------------------- //
guASFTagInfo::~guASFTagInfo()
{
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::Read( void )
{
if( guTagInfo::Read() )
{
ReadExtendedTags( m_ASFTag );
return true;
}
else
{
guLogError( wxT( "Could not read tags from file '%s'" ), m_FileName.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::Write( const int changedflag )
{
WriteExtendedTags( m_ASFTag, changedflag );
return guTagInfo::Write( changedflag );
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::CanHandleImages( void )
{
return false;
}
// -------------------------------------------------------------------------------- //
wxImage * guASFTagInfo::GetImage( void )
{
if( m_ASFTag )
{
return GetASFImage( m_ASFTag );
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::SetImage( const wxImage * image )
{
if( m_ASFTag )
{
SetASFImage( m_ASFTag, image );
}
else
return false;
return true;
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::CanHandleLyrics( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxString guASFTagInfo::GetLyrics( void )
{
if( m_ASFTag )
{
if( m_ASFTag->attributeListMap().contains( "WM/Lyrics" ) )
{
return TStringTowxString( m_ASFTag->attributeListMap()[ "WM/Lyrics" ].front().toString() );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guASFTagInfo::SetLyrics( const wxString &lyrics )
{
if( m_ASFTag )
{
m_ASFTag->removeItem( "WM/Lyrics" );
m_ASFTag->setAttribute( "WM/Lyrics", wxStringToTString( lyrics ) );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
// guGStreamerTagInfo
// -------------------------------------------------------------------------------- //
guGStreamerTagInfo::guGStreamerTagInfo( const wxString &filename ) : guTagInfo( filename )
{
guLogDebug("guGStreamerTagInfo::guGStreamerTagInfo");
if( m_TagFile && !m_TagFile->isNull() )
ReadGStreamerTags( m_TagFile->file()->name() );
}
// -------------------------------------------------------------------------------- //
guGStreamerTagInfo::~guGStreamerTagInfo()
{
guLogDebug("guGStreamerTagInfo::~guGStreamerTagInfo");
if ( m_GstTagList != NULL )
gst_tag_list_unref( (GstTagList *)m_GstTagList );
}
// -------------------------------------------------------------------------------- //
wxString guGStreamerTagInfo::GetGstStrTag( const gchar * tag )
{
gchar * gc_val;
if( (m_GstTagList != NULL) && gst_tag_list_get_string( m_GstTagList, tag, &gc_val ) ) {
wxString res = wxString::FromUTF8(gc_val);
g_free(gc_val);
return res;
}
else
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
int guGStreamerTagInfo::GetGstIntTag( const gchar * tag )
{
gint gc_val;
if( (m_GstTagList != NULL) && gst_tag_list_get_int( m_GstTagList, tag, &gc_val ) ) {
return gc_val;
}
else
return 0;
}
// -------------------------------------------------------------------------------- //
bool guGStreamerTagInfo::GetGstBoolTag( const gchar * tag )
{
gboolean gc_val;
if( (m_GstTagList != NULL) && gst_tag_list_get_boolean( m_GstTagList, tag, &gc_val ) ) {
return gc_val;
}
else
return false;
}
// -------------------------------------------------------------------------------- //
GDateTime * guGStreamerTagInfo::GetGstTimeTag( const gchar * tag )
{
if( m_GstTagList == NULL )
return NULL;
GstDateTime *dt;
GDateTime *res = NULL;
GDate *gd;
if( gst_tag_list_get_date_time( m_GstTagList, tag, &dt ) ) {
res = gst_date_time_to_g_date_time(dt);
gst_date_time_unref(dt);
}
else if( gst_tag_list_get_date( m_GstTagList, tag, &gd ) )
{
res = g_date_time_new_local( gd->year, gd->month, gd->day, 0, 0, 0 );
g_free(gd);
}
return res;
}
// -------------------------------------------------------------------------------- //
bool guGStreamerTagInfo::Read( void )
{
guLogDebug("guGStreamerTagInfo::Read");
if( ReadGStreamerTags(m_FileName) )
{
m_TrackName = GetGstStrTag( GST_TAG_TITLE );
m_ArtistName = GetGstStrTag( GST_TAG_ARTIST );
m_AlbumName = GetGstStrTag( GST_TAG_ALBUM );
m_GenreName = GetGstStrTag( GST_TAG_GENRE );
m_Comments = GetGstStrTag( GST_TAG_COMMENT );
m_Track = GetGstIntTag( GST_TAG_TRACK_NUMBER );
m_AlbumArtist = GetGstStrTag( GST_TAG_ALBUM_ARTIST );
m_Composer = GetGstStrTag( GST_TAG_COMPOSER );
GDateTime * gd = GetGstTimeTag( GST_TAG_DATE );
if( gd != NULL )
gd = GetGstTimeTag( GST_TAG_DATE_TIME );
if( gd != NULL )
{
m_Year = g_date_time_get_year( gd );
g_date_time_unref( gd );
}
m_Rating = GetGstIntTag( GST_TAG_USER_RATING );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guGStreamerTagInfo::CanHandleImages( void )
{
return true;
}
// -------------------------------------------------------------------------------- //
bool guGStreamerTagInfo::ReadGStreamerTags( const wxString &filename )
{
guLogDebug("guGStreamerTagInfo::ReadGStreamerTags");
gchar *uri;
if( gst_uri_is_valid ( filename.c_str() ) )
{
uri = g_strdup( ( const gchar * ) filename.c_str() );
}
else
{
uri = gst_filename_to_uri( filename.c_str(), NULL );
}
GError * err = NULL;
GstDiscoverer * dis = NULL;
GstDiscovererInfo * info = NULL;
dis = gst_discoverer_new( 10 * GST_SECOND, &err );
if( dis == NULL )
{
guLogWarning( wxT("gst_discoverer_new error: %s"), err->message );
g_free(uri);
return false;
}
info = gst_discoverer_discover_uri( dis, uri, &err );
g_free(uri);
if( info == NULL )
{
guLogWarning( wxT("gst_discoverer_discover_uri error: %s"), err->message );
return false;
}
m_Length = gst_discoverer_info_get_duration( info ) / 1000000;
guLogDebug("guGStreamerTagInfo::ReadGStreamerTags length: %u", m_Length);
GList *l, *slist = gst_discoverer_info_get_streams( info, g_type_from_name( "GstDiscovererAudioInfo" ) );
for( l = slist; l != NULL; l = l->next )
{
if ( !m_Bitrate )
m_Bitrate = gst_discoverer_audio_info_get_bitrate((const GstDiscovererAudioInfo*)l->data);
if ( !m_Bitrate )
m_Bitrate = gst_discoverer_audio_info_get_max_bitrate((const GstDiscovererAudioInfo*)l->data);
guLogDebug( "guGStreamerTagInfo::ReadGStreamerTags bitrate: %u", m_Bitrate );
}
gst_discoverer_stream_info_list_free(slist);
if ( m_GstTagList != NULL )
gst_tag_list_unref ( (GstTagList *)m_GstTagList );
m_GstTagList = gst_discoverer_info_get_tags( info );
if ( m_GstTagList != NULL )
{
gchar * str_tags = gst_tag_list_to_string( m_GstTagList );
guLogDebug( "guGStreamerTagInfo::ReadGStreamerTags got tags: '%s'", str_tags );
g_free( str_tags );
return !( gst_tag_list_is_empty( m_GstTagList ) );
}
else
guLogDebug( "guGStreamerTagInfo::ReadGStreamerTags tags not found" );
return false;
}
// -------------------------------------------------------------------------------- //
wxString guGStreamerTagInfo::GetLyrics( void )
{
return GetGstStrTag( GST_TAG_LYRICS );
}
// -------------------------------------------------------------------------------- //
wxImage * guGStreamerTagInfo::GetImage( void )
{
guLogDebug("guGStreamerTagInfo::GetImage");
if( m_GStreamerImage != NULL )
return m_GStreamerImage;
const char *uri, *param = (const char*)m_FileName.mb_str();
if( gst_uri_is_valid( param ) )
uri = param;
else
uri = gst_filename_to_uri( param, NULL );
wxString m_line = "uridecodebin uri=" + wxString( uri ) +
" ! jpegenc snapshot=TRUE quality=100 " +
" ! fakesink sync=false enable-last-sample=true name=sink";
guGstElementStatePtr pipeline_gp( gst_parse_launch( (const char *)m_line.mb_str(), NULL ) );
GstElement *pipeline = pipeline_gp.ptr;
if( pipeline == NULL )
return NULL;
// smrt ptr
guGstPtr<GstElement> sink_gp( gst_bin_get_by_name( GST_BIN( pipeline ), "sink" ) );
GstElement *sink = sink_gp.ptr;
if( sink == NULL )
return NULL;
GstStateChangeReturn ret = gst_element_set_state( pipeline, GST_STATE_PLAYING );
if( ret == GST_STATE_CHANGE_FAILURE )
return NULL;
// smrt ptr
guGstPtr<GstBus> bus_gp( gst_element_get_bus( pipeline ) );
GstBus *bus = bus_gp.ptr;
if( bus == NULL )
return NULL;
// weak ref for scope-limited msg
GstMessage * msg_wref;
do
{
// no msg in 5 sec => we just fail
guGstMessagePtr msg_gp( gst_bus_timed_pop( bus, 5 * GST_SECOND ) );
GstMessage *msg = msg_gp.ptr;
if( msg != NULL )
{
guLogDebug( "guGStreamerTagInfo::GetImage message type <%s>", GST_MESSAGE_TYPE_NAME( msg ) );
switch( GST_MESSAGE_TYPE( msg ) )
{
case GST_MESSAGE_STATE_CHANGED:
#ifdef GU_DEBUG
GstState old_state, new_state, pending_state;
gst_message_parse_state_changed( msg, &old_state, &new_state, &pending_state);
guLogDebug( "guGStreamerTagInfo::GetImage %s state change %s -> %s:\n",
GST_OBJECT_NAME( GST_MESSAGE_SRC( msg ) ),
gst_element_state_get_name( old_state ),
gst_element_state_get_name( new_state )
);
#endif
break;
case GST_MESSAGE_ERROR:
case GST_MESSAGE_EOS:
case GST_MESSAGE_ASYNC_DONE:
msg = NULL;
break;
default:
guLogDebug( "guGStreamerTagInfo::GetImage unknown message: %s", GST_MESSAGE_TYPE_NAME( msg ) );
break;
}
}
msg_wref = msg;
}
while( msg_wref != NULL );
GstSample * spl;
g_object_get( G_OBJECT( sink ), "last-sample", &spl, NULL) ;
// unref:g_object_unref( spl )
if( spl != NULL )
{
guLogDebug( "guGStreamerTagInfo::GetImage got the last sample" );
GstBuffer * buf = gst_sample_get_buffer( spl );
if( buf != NULL )
{
guLogDebug( "guGStreamerTagInfo::GetImage buff size: %lu",
gst_buffer_get_size( buf ) );
GstMapInfo gmi;
if( gst_buffer_map( buf, &gmi, GST_MAP_READ ) )
{
guLogDebug( "guGStreamerTagInfo::GetImage map ok" );
wxMemoryInputStream mis( gmi.data, gmi.size );
m_GStreamerImage = new wxImage( mis, wxBITMAP_TYPE_JPEG );
}
}
if( G_IS_OBJECT( spl ) )
g_object_unref( spl );
}
guLogDebug( "guGStreamerTagInfo::GetImage ret" );
if( m_GStreamerImage != NULL)
return m_GStreamerImage;
else
return NULL;
}
// -------------------------------------------------------------------------------- //
// Other functions
// -------------------------------------------------------------------------------- //
wxImage * guTagGetPicture( const wxString &filename )
{
wxImage * RetVal = NULL;
guTagInfo * TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
if( TagInfo->CanHandleImages() )
{
RetVal = TagInfo->GetImage();
}
delete TagInfo;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guTagSetPicture( const wxString &filename, wxImage * picture, const bool forcesave )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
const guCurrentTrack * CurrentTrack = MainFrame->GetCurrentTrack();
if( !forcesave && CurrentTrack && CurrentTrack->m_Loaded )
{
if( CurrentTrack->m_FileName == filename )
{
// Add the pending track change to MainFrame
MainFrame->AddPendingUpdateTrack( filename, picture, wxEmptyString, guTRACK_CHANGED_DATA_IMAGES );
return true;
}
}
bool RetVal = false;
guTagInfo * TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
if( TagInfo->CanHandleImages() )
{
RetVal = TagInfo->SetImage( picture ) && TagInfo->Write( guTRACK_CHANGED_DATA_IMAGES );
}
delete TagInfo;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guTagSetPicture( const wxString &filename, const wxString &imagefile, const bool forcesave )
{
wxImage Image( imagefile );
if( Image.IsOk() )
{
return guTagSetPicture( filename, &Image, forcesave );
}
return false;
}
// -------------------------------------------------------------------------------- //
wxString guTagGetLyrics( const wxString &filename )
{
wxString RetVal = wxEmptyString;
guTagInfo * TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
if( TagInfo->CanHandleLyrics() )
{
RetVal = TagInfo->GetLyrics();
}
delete TagInfo;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guTagSetLyrics( const wxString &filename, const wxString &lyrics, const bool forcesave )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
const guCurrentTrack * CurrentTrack = MainFrame->GetCurrentTrack();
if( !forcesave && CurrentTrack && CurrentTrack->m_Loaded )
{
if( CurrentTrack->m_FileName == filename )
{
// Add the pending track change to MainFrame
MainFrame->AddPendingUpdateTrack( filename, NULL, lyrics, guTRACK_CHANGED_DATA_LYRICS );
return true;
}
}
bool RetVal = false;
guTagInfo * TagInfo = guGetTagInfoHandler( filename );
if( TagInfo )
{
if( TagInfo->CanHandleLyrics() )
{
RetVal = TagInfo->SetLyrics( lyrics ) && TagInfo->Write( guTRACK_CHANGED_DATA_LYRICS );
}
delete TagInfo;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guUpdateTracks( const guTrackArray &tracks, const guImagePtrArray &images,
const wxArrayString &lyrics, const wxArrayInt &changedflags, const bool forcesave )
{
guMainFrame * MainFrame = guMainFrame::GetMainFrame();
// Process each Track
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
// If there is nothign to change continue with next one
int ChangedFlag = changedflags[ Index ];
if( !ChangedFlag )
continue;
const guTrack &Track = tracks[ Index ];
// Dont allow to edit tags from Cue files tracks
if( Track.m_Offset )
continue;
if( wxFileExists( Track.m_FileName ) )
{
// Prevent write to the current playing file in order to avoid segfaults specially with flac and wma files
const guCurrentTrack * CurrentTrack = MainFrame->GetCurrentTrack();
if( !forcesave && CurrentTrack && CurrentTrack->m_Loaded )
{
if( CurrentTrack->m_FileName == Track.m_FileName )
{
// Add the pending track change to MainFrame
MainFrame->AddPendingUpdateTrack( Track,
Index < (int) images.Count() ? images[ Index ] : NULL,
Index < (int) lyrics.Count() ? lyrics[ Index ] : wxT( "" ),
changedflags[ Index ] );
continue;
}
}
guTagInfo * TagInfo = guGetTagInfoHandler( Track.m_FileName );
if( !TagInfo )
{
guLogError( wxT( "There is no handler for the file '%s'" ), Track.m_FileName.c_str() );
return;
}
if( ChangedFlag & guTRACK_CHANGED_DATA_TAGS )
{
TagInfo->m_TrackName = Track.m_SongName;
TagInfo->m_AlbumArtist = Track.m_AlbumArtist;
TagInfo->m_ArtistName = Track.m_ArtistName;
TagInfo->m_AlbumName = Track.m_AlbumName;
TagInfo->m_GenreName = Track.m_GenreName;
TagInfo->m_Track = Track.m_Number;
TagInfo->m_Year = Track.m_Year;
TagInfo->m_Composer = Track.m_Composer;
TagInfo->m_Comments = Track.m_Comments;
TagInfo->m_Disk = Track.m_Disk;
}
if( ChangedFlag & guTRACK_CHANGED_DATA_RATING )
{
TagInfo->m_Rating = Track.m_Rating;
TagInfo->m_PlayCount = Track.m_PlayCount;
}
if( ( ChangedFlag & guTRACK_CHANGED_DATA_LYRICS ) && TagInfo->CanHandleLyrics() )
{
TagInfo->SetLyrics( lyrics[ Index ] );
}
if( ( ChangedFlag & guTRACK_CHANGED_DATA_IMAGES ) && TagInfo->CanHandleImages() )
{
TagInfo->SetImage( images[ Index ] );
}
TagInfo->Write( ChangedFlag );
delete TagInfo;
}
else
{
guLogMessage( wxT( "File not found for edition: '%s'" ), Track.m_FileName.c_str() );
}
}
}
// -------------------------------------------------------------------------------- //
void guUpdateImages( const guTrackArray &songs, const guImagePtrArray &images, const wxArrayInt &changedflags )
{
int Count = images.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( !songs[ Index ].m_Offset && ( changedflags[ Index ] & guTRACK_CHANGED_DATA_IMAGES ) )
guTagSetPicture( songs[ Index ].m_FileName, images[ Index ] );
}
}
// -------------------------------------------------------------------------------- //
void guUpdateLyrics( const guTrackArray &songs, const wxArrayString &lyrics, const wxArrayInt &changedflags )
{
int Count = lyrics.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( !songs[ Index ].m_Offset && ( changedflags[ Index ] & guTRACK_CHANGED_DATA_LYRICS ) )
guTagSetLyrics( songs[ Index ].m_FileName, lyrics[ Index ] );
}
}
}
// -------------------------------------------------------------------------------- //
| 94,755
|
C++
|
.cpp
| 2,551
| 29.638573
| 168
| 0.482048
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,563
|
Collections.cpp
|
anonbeat_guayadeque/src/collections/Collections.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Collections.h"
#include "Settings.h"
#include <wx/arrimpl.cpp>
#include <wx/timer.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guMediaCollectionArray )
WX_DEFINE_OBJARRAY( guManagedCollectionArray )
// -------------------------------------------------------------------------------- //
guMediaCollection::guMediaCollection( const int type )
{
m_UniqueId = wxString::Format( wxT( "%08lX" ), wxGetLocalTime() );
m_Type = type;
m_UpdateOnStart = false;
m_ScanPlaylists = true;
m_ScanFollowSymLinks = false;
m_ScanEmbeddedCovers = true;
m_EmbeddMetadata = false;
m_LastUpdate = wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
guMediaCollection::~guMediaCollection()
{
}
// -------------------------------------------------------------------------------- //
bool guMediaCollection::CheckPaths( void )
{
int Count = m_Paths.Count();
bool RetVal = Count;
for( int Index = 0; Index < Count; Index++ )
{
wxString CurPath = m_Paths[ Index ];
if( !CurPath.EndsWith( wxT( "/" ) ) )
CurPath.Append( wxT( "/" ) );
if( !wxFileExists( CurPath + guCOLLECTIONS_ID_FILENAME ) )
{
RetVal = false;
break;
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
// guManagedCollection
// -------------------------------------------------------------------------------- //
guManagedCollection::guManagedCollection( void )
{
m_Enabled = false;
m_MenuItem = NULL;
}
// -------------------------------------------------------------------------------- //
guManagedCollection::~guManagedCollection()
{
}
}
// -------------------------------------------------------------------------------- //
| 2,878
|
C++
|
.cpp
| 76
| 34.881579
| 86
| 0.499463
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,564
|
LibUpdate.cpp
|
anonbeat_guayadeque/src/collections/LibUpdate.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "LibUpdate.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "MainApp.h"
#include "MediaViewer.h"
#include "TagInfo.h"
#include "Utils.h"
#include <unistd.h>
#include <wx/event.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guLibUpdateThread::guLibUpdateThread( guMediaViewer * mediaviewer, int gaugeid, const wxString &scanpath )
{
m_MediaViewer = mediaviewer;
// m_LibPanel = mediaviewer->GetLibPanel();
m_Db = mediaviewer->GetDb();
m_MainFrame = mediaviewer->GetMainFrame();
m_GaugeId = gaugeid;
m_ScanPath = scanpath;
m_CoverSearchWords = mediaviewer->GetCoverWords();
if( scanpath.IsEmpty() )
{
m_LibPaths = mediaviewer->GetPaths();
CheckSymLinks( m_LibPaths );
}
m_LastUpdate = mediaviewer->GetLastUpdate();
m_ScanAddPlayLists = mediaviewer->GetScanPlaylists();
m_ScanEmbeddedCovers = mediaviewer->GetScanEmbeddedCovers();
m_ScanSymlinks = mediaviewer->GetScanFollowSymLinks();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY + 10 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guLibUpdateThread::~guLibUpdateThread()
{
if( !TestDestroy() )
{
if( m_MediaViewer )
{
m_MediaViewer->UpdateFinished();
}
}
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
event.SetInt( m_GaugeId );
wxPostEvent( m_MainFrame, event );
}
// -------------------------------------------------------------------------------- //
int guLibUpdateThread::ScanDirectory( wxString dirname, bool includedir )
{
wxDir Dir;
wxString FileName;
wxString LowerFileName;
bool FoundCover = false;
wxString FirstAudioFile;
if( !dirname.EndsWith( wxT( "/" ) ) )
dirname += wxT( "/" );
//guLogMessage( wxT( "Scanning dir (%i) '%s'" ), includedir, dirname.c_str() );
Dir.Open( dirname );
if( !TestDestroy() && Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( FileName[ 0 ] == '.' )
continue;
if ( !m_ScanSymlinks && IsFileSymbolicLink( dirname + FileName ) )
continue;
int FileDate = GetFileLastChangeTime( dirname + FileName );
if( Dir.Exists( dirname + FileName ) )
{
//guLogMessage( wxT( "Scanning dir '%s' : FileDate: %u -> %u\n%u Tracks found" ), ( dirname + FileName ).c_str(), m_LastUpdate, FileDate, m_TrackFiles.Count() );
ScanDirectory( dirname + FileName, includedir || ( FileDate > m_LastUpdate ) );
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
event.SetInt( m_GaugeId );
event.SetExtraLong( m_TrackFiles.Count() );
wxPostEvent( m_MainFrame, event );
}
else
{
//guLogMessage( wxT( "%s (%i): FileDate: %u -> %u" ), ( dirname + FileName ).c_str(), includedir, m_LastUpdate, FileDate );
if( includedir || ( FileDate > m_LastUpdate ) )
{
LowerFileName = FileName.Lower();
if( guIsValidAudioFile( LowerFileName ) )
{
if( !m_Db->FindDeletedFile( dirname + FileName, false ) )
{
m_TrackFiles.Add( dirname + FileName );
if( m_ScanEmbeddedCovers && FirstAudioFile.IsEmpty() )
FirstAudioFile = dirname + FileName;
}
}
else if( guIsValidImageFile( LowerFileName ) )
{
if( SearchCoverWords( LowerFileName, m_CoverSearchWords ) )
{
//guLogMessage( wxT( "Adding image '%s'" ), wxString( dirname + FileName ).c_str() );
m_ImageFiles.Add( dirname + FileName );
FoundCover = true;
}
}
else if( m_ScanAddPlayLists && guPlaylistFile::IsValidPlayList( LowerFileName ) )
{
m_PlayListFiles.Add( dirname + FileName );
}
else if( guCuePlaylistFile::IsValidFile( LowerFileName ) )
{
//
m_CueFiles.Add( dirname + FileName );
}
//else
//{
// guLogMessage( wxT( "Unknown file: '%s'"), ( dirname + FileName ).c_str() );
//}
}
}
} while( !TestDestroy() && Dir.GetNext( &FileName ) );
if( m_ScanEmbeddedCovers && !FoundCover && !FirstAudioFile.IsEmpty() )
{
m_ImageFiles.Add( FirstAudioFile );
}
}
}
else
{
guLogMessage( wxT( "Could not open the dir '%s'" ), dirname.c_str() );
}
return 1;
}
// -------------------------------------------------------------------------------- //
void GetCoversFromSamePath( const wxString &path, wxArrayString &files, wxArrayString &paths, wxArrayInt &positions )
{
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( wxPathOnly( files[ Index ] ) == path )
{
paths.Add( files[ Index ] );
positions.Add( Index );
}
else
break;
}
}
// -------------------------------------------------------------------------------- //
int GetFirstCoverPath( const wxArrayString &words, const wxArrayString &paths )
{
int WordsIndex;
int WordsCount = words.Count();
for( WordsIndex = 0; WordsIndex < WordsCount; WordsIndex++ )
{
int PathsIndex;
int PathsCount = paths.Count();
for( PathsIndex = 0; PathsIndex < PathsCount; PathsIndex++ )
{
if( paths[ PathsIndex ].Lower().Find( words[ WordsIndex ].Lower() ) != wxNOT_FOUND )
{
return PathsIndex;
}
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guLibUpdateThread::ProcessCovers( void )
{
wxCommandEvent evtup( wxEVT_MENU, ID_STATUSBAR_GAUGE_UPDATE );
evtup.SetInt( m_GaugeId );
wxCommandEvent evtmax( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
evtmax.SetInt( m_GaugeId );
wxString CoverName = m_MediaViewer->GetCoverName( wxNOT_FOUND ) + wxT( ".jpg" );
//int CoverType = m_MediaViewer->GetCoverType();
int CoverMaxSize = m_MediaViewer->GetCoverMaxSize();
int ImageCount = m_ImageFiles.Count();
m_Db->ExecuteUpdate( wxT( "BEGIN TRANSACTION;" ) );
evtmax.SetExtraLong( ImageCount );
wxPostEvent( m_MainFrame, evtmax );
while( !TestDestroy() )
{
if( !m_ImageFiles.Count() )
break;
wxArrayString CoverPaths;
wxArrayInt CoverIndexs;
GetCoversFromSamePath( wxPathOnly( m_ImageFiles[ 0 ] ), m_ImageFiles, CoverPaths, CoverIndexs );
int FirstIndex = ( CoverPaths.Count() == 1 ) ? 0 : wxMax( 0, GetFirstCoverPath( m_CoverSearchWords, CoverPaths ) );
m_Db->UpdateImageFile( CoverPaths[ FirstIndex ].ToUTF8(), CoverName.ToUTF8(), wxBITMAP_TYPE_JPEG, CoverMaxSize );
// The covers found are always at the beginning so we remove them
m_ImageFiles.RemoveAt( 0, CoverIndexs.Count() );
//guLogMessage( wxT( "%i covers left from %i " ), m_ImageFiles.Count(), ImageCount );
evtup.SetExtraLong( ImageCount - m_ImageFiles.Count() );
wxPostEvent( m_MainFrame, evtup );
}
m_Db->ExecuteUpdate( wxT( "COMMIT TRANSACTION;" ) );
}
// -------------------------------------------------------------------------------- //
guLibUpdateThread::ExitCode guLibUpdateThread::Entry()
{
int LastIndex;
wxCommandEvent evtup( wxEVT_MENU, ID_STATUSBAR_GAUGE_UPDATE );
evtup.SetInt( m_GaugeId );
wxCommandEvent evtmax( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
evtmax.SetInt( m_GaugeId );
if( m_ScanPath.IsEmpty() )
{
int Count = m_LibPaths.Count();
if( !Count )
{
guLogError( wxT( "No library directories to scan" ) );
return 0;
}
// For every directory in the library scan for new files and add them to m_TrackFiles
int Index = 0;
while( !TestDestroy() && ( Index < Count ) )
{
guLogMessage( wxT( "Doing Library Update in %s" ), m_LibPaths[ Index ].c_str() );
ScanDirectory( m_LibPaths[ Index ] );
Index++;
}
}
else
{
ScanDirectory( m_ScanPath, true );
}
bool EmbeddMetadata = m_MediaViewer->GetMediaCollection()->m_EmbeddMetadata;
// For every new track file update it in the database
int Count = m_TrackFiles.Count();
if( Count )
{
m_Db->ExecuteUpdate( wxT( "BEGIN TRANSACTION;" ) );
evtmax.SetExtraLong( Count );
wxPostEvent( m_MainFrame, evtmax );
LastIndex = -1;
int Index = 0;
while( !TestDestroy() )
{
//guLogMessage( wxT( "%i - %i" ), Index, Count );
if( ( Index >= Count ) )
break;
//guLogMessage( wxT( "Scanning: '%s'" ), m_TrackFiles[ Index ].c_str() );
m_Db->ReadFileTags( m_TrackFiles[ Index ], EmbeddMetadata );
//Sleep( 1 );
Index++;
if( Index > LastIndex )
{
evtup.SetExtraLong( Index );
wxPostEvent( m_MainFrame, evtup );
LastIndex = Index + 5;
}
}
m_Db->ExecuteUpdate( wxT( "COMMIT TRANSACTION;" ) );
}
Count = m_CueFiles.Count();
if( Count )
{
m_Db->ExecuteUpdate( wxT( "BEGIN TRANSACTION;" ) );
evtmax.SetExtraLong( Count );
wxPostEvent( m_MainFrame, evtmax );
for( int Index = 0; Index < Count; Index++ )
{
//
// Delete all files from the same cue files
//
wxString query = wxT( "DELETE FROM songs WHERE song_path = '" );
query += escape_query_str( wxPathOnly( m_CueFiles[ Index ] + wxT( "/" ) ) );
query += wxT( "' AND song_offset > 0" );
m_Db->ExecuteUpdate( query );
//guLogMessage( wxT( "DELETE:\n%s" ), query.c_str() );
}
LastIndex = -1;
int Index = 0;
while( !TestDestroy() )
{
//guLogMessage( wxT( "%i - %i" ), Index, Count );
if( ( Index >= Count ) )
break;
//guLogMessage( wxT( "Scanning: '%s'" ), m_TrackFiles[ Index ].c_str() );
m_Db->ReadFileTags( m_CueFiles[ Index ], EmbeddMetadata );
//Sleep( 1 );
Index++;
if( Index > LastIndex )
{
evtup.SetExtraLong( Index );
wxPostEvent( m_MainFrame, evtup );
LastIndex = Index + 5;
}
}
m_Db->ExecuteUpdate( wxT( "COMMIT TRANSACTION;" ) );
}
ProcessCovers();
Count = m_PlayListFiles.Count();
if( Count )
{
m_Db->ExecuteUpdate( wxT( "BEGIN TRANSACTION;" ) );
evtmax.SetExtraLong( Count );
wxPostEvent( m_MainFrame, evtmax );
LastIndex = -1;
int Index = 0;
while( !TestDestroy() )
{
//guLogMessage( wxT( "%i - %i" ), Index, Count );
if( ( Index >= Count ) )
break;
guPlaylistFile PlayList( m_PlayListFiles[ Index ] );
wxArrayInt PlayListIds;
int ItemTrackId;
int ItemIndex;
int ItemCount;
if( ( ItemCount = PlayList.Count() ) )
{
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
if( wxFileExists( PlayList.GetItem( ItemIndex ).m_Location ) )
{
ItemTrackId = m_Db->FindTrackFile( PlayList.GetItem( ItemIndex ).m_Location, NULL );
if( ItemTrackId )
{
PlayListIds.Add( ItemTrackId );
}
}
}
if( PlayListIds.Count() )
{
if( m_Db->GetStaticPlayList( m_PlayListFiles[ Index ] ) == wxNOT_FOUND )
{
m_Db->CreateStaticPlayList( m_PlayListFiles[ Index ], PlayListIds );
wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
evt.SetClientData( ( void * ) m_MediaViewer );
wxPostEvent( m_MainFrame, evt );
}
}
}
Index++;
if( Index > LastIndex )
{
evtup.SetExtraLong( Index );
wxPostEvent( m_MainFrame, evtup );
LastIndex = Index + 5;
}
}
m_Db->ExecuteUpdate( wxT( "COMMIT TRANSACTION;" ) );
}
//
// This cant be called here as wxBitmap do X11 calls and this can only be done from the main
// thread. So we must call DoCleanUp from the main thread once this thread is finished.
// in the OnLibraryUpdated Event handler
//
// delete all orphans entries
// m_Db->DoCleanUp();
return 0;
}
// -------------------------------------------------------------------------------- //
// guLibCleanThread
// -------------------------------------------------------------------------------- //
guLibCleanThread::guLibCleanThread( guMediaViewer * mediaviewer )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_MainFrame = mediaviewer->GetMainFrame();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY );
Run();
}
}
// -------------------------------------------------------------------------------- //
guLibCleanThread::~guLibCleanThread()
{
if( !TestDestroy() )
{
wxCommandEvent event( wxEVT_MENU, ID_LIBRARY_CLEANFINISHED );
//event.SetEventObject( ( wxObject * ) this );
//event.SetClientData( ( void * ) m_LibPanel );
wxPostEvent( m_MediaViewer, event );
}
}
// -------------------------------------------------------------------------------- //
guLibCleanThread::ExitCode guLibCleanThread::Entry()
{
wxString query;
wxArrayInt SongsToDel;
wxArrayInt CoversToDel;
wxSQLite3ResultSet dbRes;
wxString FileName;
wxArrayString LibPaths = m_MediaViewer->GetPaths();
if( !TestDestroy() )
{
CheckSymLinks( LibPaths );
query = wxT( "SELECT DISTINCT song_id, song_filename, song_path FROM songs " );
dbRes = m_Db->ExecuteQuery( query );
while( !TestDestroy() && dbRes.NextRow() )
{
FileName = dbRes.GetString( 2 ) + dbRes.GetString( 1 );
//guLogMessage( wxT( "Checking %s" ), FileName.c_str() );
if( !wxFileExists( FileName ) || !CheckFileLibPath( LibPaths, FileName ) )
{
SongsToDel.Add( dbRes.GetInt( 0 ) );
}
}
dbRes.Finalize();
if( !TestDestroy() )
{
query = wxT( "SELECT DISTINCT cover_id, cover_path FROM covers;" );
dbRes = m_Db->ExecuteQuery( query );
while( !TestDestroy() && dbRes.NextRow() )
{
if( !wxFileExists( dbRes.GetString( 1 ) ) )
{
CoversToDel.Add( dbRes.GetInt( 0 ) );
}
}
dbRes.Finalize();
if( !TestDestroy() )
{
wxArrayString Queries;
//m_Db->CleanItems( SongsToDel, CoversToDel );
if( SongsToDel.Count() )
{
Queries.Add( wxT( "DELETE FROM songs WHERE " ) + ArrayToFilter( SongsToDel, wxT( "song_id" ) ) );
}
if( CoversToDel.Count() )
{
Queries.Add( wxT( "DELETE FROM covers WHERE " ) + ArrayToFilter( CoversToDel, wxT( "cover_id" ) ) );
}
// Delete all posible orphan entries
Queries.Add( wxT( "DELETE FROM covers WHERE cover_id NOT IN ( SELECT DISTINCT song_coverid FROM songs );" ) );
Queries.Add( wxT( "DELETE FROM plsets WHERE plset_type = 0 AND plset_songid > 0 AND plset_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" ) );
Queries.Add( wxT( "DELETE FROM settags WHERE settag_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" ) );
int Count = Queries.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( TestDestroy() )
break;
//guLogMessage( wxT( "Executing: '%s'" ), Queries[ Index ].c_str() );
m_Db->ExecuteUpdate( Queries[ Index ] );
}
//m_Db->LoadCache();
}
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 18,195
|
C++
|
.cpp
| 467
| 29.852248
| 172
| 0.520202
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,565
|
Transcode.cpp
|
anonbeat_guayadeque/src/copyto/Transcode.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Transcode.h"
#include "EventCommandIds.h"
#include "TagInfo.h"
#include "Utils.h"
#include "Version.h"
#include "PortableMedia.h"
#include <wx/filefn.h>
#include <wx/filename.h>
#include <wx/uri.h>
namespace Guayadeque {
extern "C" {
// -------------------------------------------------------------------------------- //
static gboolean gst_bus_async_callback( GstBus * bus, GstMessage * message, guTranscodeThread * pobj )
{
//guLogMessage( wxT( "Got gstreamer message %08X = '%s'" ), GST_MESSAGE_TYPE( message ), wxString( GST_MESSAGE_TYPE_NAME(message), wxConvUTF8 ).c_str() );
switch( GST_MESSAGE_TYPE( message ) )
{
case GST_MESSAGE_ERROR :
{
GError * err;
gchar * debug;
gst_message_parse_error( message, &err, &debug );
guLogError( wxT( "Transcode gstreamer error '%s'\n'%s'" ),
wxString( err->message, wxConvUTF8 ).c_str(),
wxString( debug, wxConvUTF8 ).c_str() );
g_error_free( err );
g_free( debug );
pobj->SetError( true );
pobj->Stop();
break;
}
// case GST_MESSAGE_STATE_CHANGED:
// {
// // GST_STATE_VOID_PENDING = 0,
// // GST_STATE_NULL = 1,
// // GST_STATE_READY = 2,
// // GST_STATE_PAUSED = 3,
// // GST_STATE_PLAYING = 4
// GstState oldstate, newstate, pendingstate;
// gst_message_parse_state_changed( message, &oldstate, &newstate, &pendingstate );
//
// guLogMessage( wxT( "State changed %u -> %u (%u)" ), oldstate, newstate, pendingstate );
// if( pendingstate == GST_STATE_VOID_PENDING )
// {
// guLogMessage( wxT( "State changed %u -> %u (%u)" ), oldstate, newstate, pendingstate );
// }
// break;
// }
case GST_MESSAGE_EOS :
{
//guLogMessage( wxT( "Transcode EOS Detected..." ) );
pobj->Stop();
break;
}
default:
break;
}
return TRUE;
}
// -------------------------------------------------------------------------------- //
static void on_pad_added( GstElement * decodebin, GstPad * pad, GstElement * conv )
{
GstCaps * caps;
GstStructure * str;
GstPad * convpad;
//guLogMessage( wxT( "New pad created..." ) );
convpad = gst_element_get_static_pad( conv, "sink" );
if( GST_PAD_IS_LINKED( convpad ) )
{
g_object_unref( convpad );
return;
}
/* check media type */
caps = gst_pad_query_caps( pad, NULL );
str = gst_caps_get_structure( caps, 0 );
if( !g_strrstr( gst_structure_get_name( str ), "audio" ) )
{
gst_caps_unref( caps );
gst_object_unref( convpad );
return;
}
gst_caps_unref( caps );
//guLogMessage( wxT( "Linked composer and converter..." ) );
/* link'n'play */
gst_pad_link( pad, convpad );
g_object_unref( convpad );
}
// -------------------------------------------------------------------------------- //
static bool seek_timeout( guTranscodeThread * transcodethread )
{
transcodethread->DoStartSeek();
return false;
}
}
// -------------------------------------------------------------------------------- //
// guTranscodeThread
// -------------------------------------------------------------------------------- //
guTranscodeThread::guTranscodeThread( const guTrack * track, const wxChar * target,
const int format, const int quality )
{
m_Track = track;
m_Target = wxString( target );
m_TempName = wxFileName::CreateTempFileName( wxT( "guayadeque" ) ) + wxT( "." ) + m_Target.AfterLast( '.' );
guLogMessage( wxT( "The temporary filename is %s" ), m_TempName.c_str() );
m_Format = format;
m_Quality = quality;
m_StartPos = track->m_Offset;
m_Length = track->m_Length;
m_SeekTimerId = 0;
guLogMessage( wxT( "Transcode %i - %i '%s' => '%s'\n:::: %i => %i" ),
format, quality, track->m_FileName.c_str(), target, m_StartPos, m_Length );
m_Running = false;
m_HasError = false;
if( m_Format == guTRANSCODE_FORMAT_KEEP )
{
int FileFormat = guGetTranscodeFileFormat( m_Track->m_FileName.Lower().AfterLast( wxT( '.' ) ) );
switch( FileFormat )
{
case guPORTABLEMEDIA_AUDIO_FORMAT_MP3 :
m_Format = guTRANSCODE_FORMAT_MP3;
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_AAC :
m_Format = guTRANSCODE_FORMAT_AAC;
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_WMA :
m_Format = guTRANSCODE_FORMAT_WMA;
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_OGG :
m_Format = guTRANSCODE_FORMAT_OGG;
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_FLAC :
m_Format = guTRANSCODE_FORMAT_FLAC;
break;
default :
m_Format = guTRANSCODE_FORMAT_MP3;
}
}
BuildPipeline();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guTranscodeThread::~guTranscodeThread()
{
if( GST_IS_ELEMENT( m_Pipeline ) )
{
gst_element_set_state( m_Pipeline, GST_STATE_NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_remove_watch( bus );
gst_object_unref( G_OBJECT( bus ) );
gst_object_unref( GST_OBJECT( m_Pipeline ) );
}
}
int guTranscodeMp3Bitrates[] = {
128,
320,
256,
192,
160,
128,
96,
64
};
float guTranscodeOggQuality[] = {
0.6,
1,
0.9,
0.8,
0.7,
0.6,
0.5,
0.2
};
int guTranscodeFlacQuality[] = {
4,
8,
7,
6,
5,
4,
3,
1
};
unsigned long guTranscodeWmaBitrates[] = {
128000,
320000,
256000,
192000,
160000,
128000,
96000,
64000
};
// -------------------------------------------------------------------------------- //
wxArrayString TranscodeFormatStrings;
wxArrayString IpodTranscodeFormatStrings;
wxArrayString TranscodeQualityStrings;
// -------------------------------------------------------------------------------- //
int guGetTranscodeFileFormat( const wxString &filetype )
{
if( filetype == wxT( "mp3" ) )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_MP3;
}
else if( filetype == wxT( "ogg" ) || filetype == wxT( "oga" ) )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_OGG;
}
else if( filetype == wxT( "flac" ) )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_FLAC;
}
else if( filetype == wxT( "m4a" ) || filetype == wxT( "m4b" ) ||
filetype == wxT( "aac" ) || filetype == wxT( "mp4" ) ||
filetype == wxT( "m4p" ) )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_AAC;
}
else if( filetype == wxT( "wma" ) )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_WMA;
}
return guTRANSCODE_FORMAT_KEEP;
}
// -------------------------------------------------------------------------------- //
wxArrayString guTranscodeFormatStrings( const bool isipod )
{
if( isipod )
{
if( !IpodTranscodeFormatStrings.Count() )
{
IpodTranscodeFormatStrings.Add( wxT( "mp3" ) );
IpodTranscodeFormatStrings.Add( wxT( "m4a" ) );
}
return IpodTranscodeFormatStrings;
}
if( !TranscodeFormatStrings.Count() )
{
TranscodeFormatStrings.Add( _( "Keep Format" ) );
TranscodeFormatStrings.Add( wxT( "mp3" ) );
TranscodeFormatStrings.Add( wxT( "ogg" ) );
TranscodeFormatStrings.Add( wxT( "flac" ) );
TranscodeFormatStrings.Add( wxT( "m4a" ) );
TranscodeFormatStrings.Add( wxT( "wma" ) );
}
return TranscodeFormatStrings;
}
// -------------------------------------------------------------------------------- //
wxString guTranscodeFormatString( const int format )
{
if( !TranscodeFormatStrings.Count() )
guTranscodeFormatStrings();
return TranscodeFormatStrings[ format ];
}
// -------------------------------------------------------------------------------- //
wxArrayString guTranscodeQualityStrings( void )
{
if( !TranscodeQualityStrings.Count() )
{
TranscodeQualityStrings.Add( _( "Keep Quality" ) );
TranscodeQualityStrings.Add( _( "Very High" ) );
TranscodeQualityStrings.Add( _( "High" ) );
TranscodeQualityStrings.Add( _( "Very Good" ) );
TranscodeQualityStrings.Add( _( "Good" ) );
TranscodeQualityStrings.Add( _( "Normal" ) );
TranscodeQualityStrings.Add( _( "Low" ) );
TranscodeQualityStrings.Add( _( "Very Low" ) );
}
return TranscodeQualityStrings;
}
// -------------------------------------------------------------------------------- //
wxString guTranscodeQualityString( const int quality )
{
if( !TranscodeQualityStrings.Count() )
guTranscodeQualityStrings();
return TranscodeQualityStrings[ quality ];
}
// -------------------------------------------------------------------------------- //
bool guTranscodeThread::BuildEncoder( GstElement ** enc, GstElement ** mux )
{
switch( m_Format )
{
case guTRANSCODE_FORMAT_MP3 :
{
//guLogMessage( wxT( "Creating mp3 encoder with %i bitrate" ), guTranscodeMp3Bitrates[ m_Quality ] );
* enc = gst_element_factory_make( "lamemp3enc", "guTransLame" );
if( GST_IS_ELEMENT( * enc ) )
{
g_object_set( * enc, "target", 1, NULL );
g_object_set( * enc, "cbr", TRUE, NULL );
g_object_set( * enc, "bitrate", guTranscodeMp3Bitrates[ m_Quality ], NULL );
return true;
}
* enc = NULL;
break;
}
case guTRANSCODE_FORMAT_OGG :
{
* enc = gst_element_factory_make( "vorbisenc", "guTransVorbis" );
if( GST_IS_ELEMENT( * enc ) )
{
g_object_set( * enc, "quality", guTranscodeOggQuality[ m_Quality ], NULL );
* mux = gst_element_factory_make( "oggmux", "guTransOggMux" );
if( GST_IS_ELEMENT( * mux ) )
{
return true;
}
g_object_unref( * enc );
* enc = NULL;
}
break;
}
case guTRANSCODE_FORMAT_FLAC :
{
* enc = gst_element_factory_make( "flacenc", "guTransFlac" );
if( GST_IS_ELEMENT( * enc ) )
{
g_object_set( * enc, "quality", guTranscodeFlacQuality[ m_Quality ], NULL );
return true;
}
break;
}
case guTRANSCODE_FORMAT_AAC :
{
* enc = gst_element_factory_make( "faac", "guTransAAC" );
if( GST_IS_ELEMENT( * enc ) )
{
g_object_set( * enc, "profile", 2, NULL );
g_object_set( * enc, "bitrate", guTranscodeWmaBitrates[ m_Quality ], NULL );
* mux = gst_element_factory_make( "ffmux_mp4", "guTransAACMux" );
if( GST_IS_ELEMENT( * mux ) )
{
return true;
}
g_object_unref( * enc );
* enc = NULL;
}
break;
}
case guTRANSCODE_FORMAT_WMA :
{
* enc = gst_element_factory_make( "ffenc_wmav2", "guTransWMA" );
if( GST_IS_ELEMENT( * enc ) )
{
g_object_set( * enc, "bitrate", guTranscodeWmaBitrates[ m_Quality ], NULL );
* mux = gst_element_factory_make( "ffmux_asf", "guTransWMAMux" );
if( GST_IS_ELEMENT( * mux ) )
{
return true;
}
g_object_unref( * enc );
* enc = NULL;
}
break;
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool SetStateAndWait( GstElement * element, GstState state )
{
GstStateChangeReturn ChangeState = gst_element_set_state( element, state );
if( ChangeState == GST_STATE_CHANGE_ASYNC )
{
gst_element_get_state( element, NULL, NULL, GST_CLOCK_TIME_NONE );
return true;
}
return ChangeState == GST_STATE_CHANGE_SUCCESS;
}
// -------------------------------------------------------------------------------- //
void guTranscodeThread::BuildPipeline( void )
{
m_Pipeline = gst_pipeline_new( "guTransPipeline" );
if( GST_IS_ELEMENT( m_Pipeline ) )
{
GstElement * src;
if( m_Track->m_Type == guTRACK_TYPE_AUDIOCD )
{
src = gst_element_make_from_uri( GST_URI_SRC, "cdda://", "guTransSource", NULL );
}
else
{
src = gst_element_factory_make( "giosrc", "guTransSource" );
}
if( GST_IS_ELEMENT( src ) )
{
if( m_Track->m_Type != guTRACK_TYPE_AUDIOCD )
{
wxString Location;
wxURI URI( m_Track->m_FileName );
if( URI.IsReference() )
{
Location = wxT( "file://" ) + m_Track->m_FileName;
}
else
{
if( !URI.HasScheme() )
{
Location = wxT( "http://" ) + m_Track->m_FileName;
}
else
{
Location = m_Track->m_FileName;
}
}
Location.Replace( " ", "%20", true );
guLogMessage( wxT( "Transode source location: '%s'" ), Location.c_str() );
g_object_set( G_OBJECT( src ), "location", ( const char * ) Location.mb_str( wxConvFile ), NULL );
}
GstElement * dec;
dec = gst_element_factory_make( "decodebin", "guTransDecoder" );
if( GST_IS_ELEMENT( dec ) )
{
GstElement * conv;
conv = gst_element_factory_make( "audioconvert", "guTransAudioConv" );
if( GST_IS_ELEMENT( conv ) )
{
GstElement * enc = NULL;
GstElement * mux = NULL;
if( BuildEncoder( &enc, &mux ) )
{
GstElement * filesink;
filesink = gst_element_factory_make( "filesink", "guTransFileSink" );
if( GST_IS_ELEMENT( filesink ) )
{
g_object_set( filesink, "location", ( const char * ) m_TempName.mb_str( wxConvFile ), NULL );
if( mux )
{
gst_bin_add_many( GST_BIN( m_Pipeline ), src, dec, conv, enc, mux, filesink, NULL );
}
else
{
gst_bin_add_many( GST_BIN( m_Pipeline ), src, dec, conv, enc, filesink, NULL );
}
g_object_set( m_Pipeline, "async-handling", true, NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_add_watch( bus, ( GstBusFunc ) gst_bus_async_callback, this );
gst_object_unref( G_OBJECT( bus ) );
if( gst_element_link( src, dec ) )
{
g_signal_connect( dec, "pad-added", G_CALLBACK( on_pad_added ), conv );
if( mux )
{
gst_element_link_many( conv, enc, mux, filesink, NULL );
}
else
{
gst_element_link_many( conv, enc, filesink, NULL );
}
if( m_Track->m_Type == guTRACK_TYPE_AUDIOCD )
{
g_object_set( src, "mode", 0, NULL );
g_object_set( src, "track", m_Track->m_Number, NULL );
}
SetStateAndWait( m_Pipeline, GST_STATE_READY );
return;
}
else
{
guLogError( wxT( "couldnt link the source and the decoder" ) );
}
gst_object_unref( filesink );
}
else
{
guLogError( wxT( "Error creating the transcode filesink" ) );
}
gst_object_unref( enc );
if( mux )
{
gst_object_unref( mux );
}
}
else
{
guLogError( wxT( "Error creating the transcode encoder" ) );
}
gst_object_unref( conv );
}
else
{
guLogError( wxT( "Error creating the transcode converter" ) );
}
gst_object_unref( dec );
}
else
{
guLogError( wxT( "Error creating the transcode decoder" ) );
}
gst_object_unref( src );
}
else
{
guLogError( wxT( "Error creating the transcode source" ) );
}
gst_object_unref( m_Pipeline );
m_Pipeline = NULL;
}
else
{
guLogError( wxT( "Error creating the transcode pipeline" ) );
}
m_HasError = true;
}
// -------------------------------------------------------------------------------- //
bool guTranscodeThread::DoStartSeek( void )
{
guLogMessage( wxT( "DoStartSeek( %i )" ), m_StartPos );
if( GST_IS_ELEMENT( m_Pipeline ) )
{
GstSeekFlags SeekFlags = GstSeekFlags( GST_SEEK_FLAG_FLUSH |
GST_SEEK_FLAG_KEY_UNIT |
GST_SEEK_FLAG_ACCURATE );
gst_element_seek_simple( m_Pipeline, GST_FORMAT_TIME, SeekFlags, m_StartPos * GST_MSECOND );
m_SeekTimerId = 0;
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
guTranscodeThread::ExitCode guTranscodeThread::Entry()
{
if( m_Pipeline )
{
SetStateAndWait( m_Pipeline, GST_STATE_PAUSED );
if( m_StartPos )
{
m_SeekTimerId = g_timeout_add( 150, GSourceFunc( seek_timeout ), this );
}
// If the seek timer was created...
while( m_SeekTimerId )
{
// Wait for the seek to complete
Sleep( 100 );
}
//gst_element_set_state( m_Pipeline, GST_STATE_PLAYING );
SetStateAndWait( m_Pipeline, GST_STATE_PLAYING );
Sleep( 200 );
m_Running = true;
while( !TestDestroy() && m_Running )
{
if( m_StartPos )
{
wxFileOffset Position = 0;
if( !gst_element_query_position( m_Pipeline, GST_FORMAT_TIME, ( gint64 * ) &Position ) )
{
wxLogDebug( wxT( "Could not get the position" ) );
}
Position /= GST_MSECOND;
wxLogDebug( wxT( "Position: %lli" ), Position );
if( Position > m_StartPos + m_Length )
{
wxLogDebug( wxT( "Reached the end of the track %i %lli %i" ), m_StartPos, Position, m_Length );
Stop();
}
}
Sleep( 30 );
}
if( !TestDestroy() )
{
SetStateAndWait( m_Pipeline, GST_STATE_NULL );
gst_object_unref( GST_OBJECT( m_Pipeline ) );
m_Pipeline = NULL;
Sleep( 500 );
WriteTags();
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
void guTranscodeThread::WriteTags()
{
int WriteFlags = guTRACK_CHANGED_DATA_TAGS;
guTagInfo * OutTagInfo = guGetTagInfoHandler( m_TempName );
if( OutTagInfo )
{
if( !m_StartPos && m_Track->m_Type != guTRACK_TYPE_AUDIOCD )
{
guTagInfo * InTagInfo = guGetTagInfoHandler( m_Track->m_FileName );
if( InTagInfo )
{
InTagInfo->Read();
OutTagInfo->m_TrackName = InTagInfo->m_TrackName;
OutTagInfo->m_GenreName = InTagInfo->m_GenreName;
OutTagInfo->m_ArtistName = InTagInfo->m_ArtistName;
OutTagInfo->m_AlbumArtist = InTagInfo->m_AlbumArtist;
OutTagInfo->m_AlbumName = InTagInfo->m_AlbumName;
OutTagInfo->m_Composer = InTagInfo->m_Composer;
OutTagInfo->m_Comments = InTagInfo->m_Comments;
OutTagInfo->m_Track = InTagInfo->m_Track;
OutTagInfo->m_Year = InTagInfo->m_Year;
OutTagInfo->m_Disk = InTagInfo->m_Disk;
OutTagInfo->m_Rating = InTagInfo->m_Rating;
OutTagInfo->m_PlayCount = InTagInfo->m_PlayCount;
OutTagInfo->m_TrackLabels = InTagInfo->m_TrackLabels;
OutTagInfo->m_TrackLabelsStr = InTagInfo->m_TrackLabelsStr;
OutTagInfo->m_ArtistLabels = InTagInfo->m_ArtistLabels;
OutTagInfo->m_ArtistLabelsStr = InTagInfo->m_ArtistLabelsStr;
OutTagInfo->m_AlbumLabels = InTagInfo->m_AlbumLabels;
OutTagInfo->m_AlbumLabelsStr = InTagInfo->m_AlbumLabelsStr;
OutTagInfo->m_Compilation = InTagInfo->m_Compilation;
if( !InTagInfo->m_TrackLabelsStr.IsEmpty() ||
!InTagInfo->m_ArtistLabelsStr.IsEmpty() ||
!InTagInfo->m_AlbumLabelsStr.IsEmpty() )
{
WriteFlags |= guTRACK_CHANGED_DATA_LABELS;
}
delete InTagInfo;
}
else
{
guLogMessage( wxT( "Could not get the tag handler for %s" ), m_Track->m_FileName.c_str() );
}
}
else
{
OutTagInfo->m_TrackName = m_Track->m_SongName;
OutTagInfo->m_GenreName = m_Track->m_GenreName;
OutTagInfo->m_ArtistName = m_Track->m_ArtistName;
OutTagInfo->m_AlbumArtist = m_Track->m_AlbumArtist;
OutTagInfo->m_AlbumName = m_Track->m_AlbumName;
OutTagInfo->m_Composer = m_Track->m_Composer;
OutTagInfo->m_Comments = m_Track->m_Comments;
OutTagInfo->m_Track = m_Track->m_Number;
OutTagInfo->m_Year = m_Track->m_Year;
OutTagInfo->m_Disk = m_Track->m_Disk;
OutTagInfo->m_Rating = m_Track->m_Rating;
OutTagInfo->m_PlayCount = m_Track->m_PlayCount;
}
if( OutTagInfo->m_Rating != wxNOT_FOUND )
{
WriteFlags |= guTRACK_CHANGED_DATA_RATING;
}
OutTagInfo->Write( WriteFlags );
delete OutTagInfo;
if( !wxCopyFile( m_TempName, m_Target ) )
{
guLogMessage( wxT( "Could not create the file %s" ), m_Target.c_str() );
}
wxRemoveFile( m_TempName );
}
}
// -------------------------------------------------------------------------------- //
void guTranscodeThread::Stop( void )
{
m_Running = false;
}
}
// -------------------------------------------------------------------------------- //
| 24,171
|
C++
|
.cpp
| 673
| 27.191679
| 158
| 0.498847
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,566
|
CopyTo.cpp
|
anonbeat_guayadeque/src/copyto/CopyTo.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CopyTo.h"
#include "Images.h"
#include "iPodMedia.h"
#include "TagInfo.h"
#include "Transcode.h"
#include <wx/tokenzr.h>
#include <wx/arrimpl.cpp>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guCopyToActionArray )
// -------------------------------------------------------------------------------- //
// guCopyToAction
// -------------------------------------------------------------------------------- //
guCopyToAction::guCopyToAction()
{
m_Type = guCOPYTO_ACTION_NONE;
m_Tracks = NULL;
m_Format = wxNOT_FOUND;
m_Quality = wxNOT_FOUND;
m_MoveFiles = false;
m_Db = NULL;
// m_PortableMediaViewCtrl = NULL;
}
// -------------------------------------------------------------------------------- //
guCopyToAction::guCopyToAction( guTrackArray * tracks, guMediaViewer * mediaviewer, const wxString &destdir, const wxString &pattern, int format, int quality, bool movefiles )
{
//guLogMessage( wxT( "guCopyToAction %li files : delete = %i" ), tracks->Count(), movefiles );
m_Type = guCOPYTO_ACTION_COPYTO;
m_Tracks = tracks;
m_MediaViewer = mediaviewer;
m_Db = mediaviewer ? mediaviewer->GetDb() : NULL;
m_PlayListFile = NULL;
m_DestDir = destdir;
m_Pattern = pattern;
m_Format = format;
m_Quality = quality;
m_MoveFiles = movefiles;
// m_PortableMediaViewCtrl = NULL;
if( !m_DestDir.EndsWith( wxT( "/" ) ) )
m_DestDir.Append( wxT( "/" ) );
}
// -------------------------------------------------------------------------------- //
guCopyToAction::guCopyToAction( guTrackArray * tracks, guMediaViewer * mediaviewer )
{
m_Type = guCOPYTO_ACTION_COPYTODEVICE;
m_Tracks = tracks;
m_MoveFiles = false;
m_Db = mediaviewer->GetDb();
m_PlayListFile = NULL;
m_MediaViewer = mediaviewer;
#ifdef WITH_LIBGPOD_SUPPORT
if( mediaviewer->GetType() == guMEDIA_COLLECTION_TYPE_IPOD )
{
m_Type = guCOPYTO_ACTION_COPYTOIPOD;
guLogMessage( wxT( "Its a iPod Device" ) );
}
#endif
m_Pattern = mediaviewer->Pattern();
m_Format = mediaviewer->TranscodeFormat();
m_Quality = mediaviewer->TranscodeQuality();
m_DestDir = mediaviewer->AudioPath();
m_MoveFiles = mediaviewer->MoveFiles();
if( m_DestDir.EndsWith( wxT( "//" ) ) )
m_DestDir.RemoveLast();
else if( !m_DestDir.EndsWith( wxT( "/" ) ) )
m_DestDir.Append( wxT( "/" ) );
m_CoverFormats = mediaviewer->CoverFormats();
m_CoverSize = mediaviewer->CoverSize();
m_CoverName = mediaviewer->CoverName();
}
// -------------------------------------------------------------------------------- //
guCopyToAction::guCopyToAction( wxString * playlistpath, guMediaViewer * mediaviewer )
{
m_Type = guCOPYTO_ACTION_COPYTODEVICE;
m_Tracks = new guTrackArray();
m_MoveFiles = false;
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_PlayListFile = new guPlaylistFile( * playlistpath );
m_PlayListFile->SetName( * playlistpath );
#ifdef WITH_LIBGPOD_SUPPORT
if( mediaviewer->GetType() == guMEDIA_COLLECTION_TYPE_IPOD )
m_Type = guCOPYTO_ACTION_COPYTOIPOD;
#endif
m_Format = mediaviewer->TranscodeFormat();
m_Quality = mediaviewer->TranscodeQuality();
m_Pattern = mediaviewer->Pattern();
m_MoveFiles = mediaviewer->MoveFiles();
m_DestDir = mediaviewer->AudioPath();
// wxArrayString AudioFolders = wxStringTokenize( PortableMediaDevice->AudioFolders(), wxT( "," ) );
// m_DestDir += AudioFolders[ 0 ].Trim( true ).Trim( false );
if( m_DestDir.EndsWith( wxT( "//" ) ) )
m_DestDir.RemoveLast();
else if( !m_DestDir.EndsWith( wxT( "/" ) ) )
m_DestDir.Append( wxT( "/" ) );
m_CoverFormats = mediaviewer->CoverFormats();
m_CoverSize = mediaviewer->CoverSize();
m_CoverName = mediaviewer->CoverName();
int Count = m_PlayListFile->Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack * CurTrack = new guTrack();
if( m_Db->FindTrackFile( m_PlayListFile->GetItem( Index ).m_Location, CurTrack ) )
{
m_Tracks->Add( CurTrack );
}
else
{
delete CurTrack;
}
}
//
delete playlistpath;
}
// -------------------------------------------------------------------------------- //
guCopyToAction::~guCopyToAction()
{
if( m_Tracks )
{
delete m_Tracks;
}
if( m_PlayListFile )
{
delete m_PlayListFile;
}
}
// -------------------------------------------------------------------------------- //
// guCopyToThread
// -------------------------------------------------------------------------------- //
guCopyToThread::guCopyToThread( guMainFrame * mainframe, int gaugeid )
{
m_MainFrame = mainframe;
m_GaugeId = gaugeid;
m_CopyToActions = new guCopyToActionArray();
m_CurrentFile = 0;
m_FileCount = 0;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
}
}
// -------------------------------------------------------------------------------- //
guCopyToThread::~guCopyToThread()
{
wxCommandEvent Event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
Event.SetInt( m_GaugeId );
wxPostEvent( m_MainFrame, Event );
if( m_CopyToActions )
{
delete m_CopyToActions;
}
if( !TestDestroy() )
{
m_MainFrame->CopyToThreadFinished();
}
}
// -------------------------------------------------------------------------------- //
void guCopyToThread::AddAction( guTrackArray * tracks, guMediaViewer * mediaviewer, const wxString &destdir, const wxString &pattern, int format, int quality, bool movefiles )
{
//guLogMessage( wxT( "AddAction %li files : delete = %i" ), tracks->Count(), movefiles );
guCopyToAction * CopyToAction = new guCopyToAction( tracks, mediaviewer, destdir, pattern, format, quality, movefiles );
if( CopyToAction )
{
m_CopyToActionsMutex.Lock();
m_CopyToActions->Add( CopyToAction );
m_FileCount += CopyToAction->Count();
m_CopyToActionsMutex.Unlock();
if( !IsRunning() )
{
Run();
}
}
}
// -------------------------------------------------------------------------------- //
void guCopyToThread::AddAction( guTrackArray * tracks, guMediaViewer * mediaviewer )
{
guCopyToAction * CopyToAction = new guCopyToAction( tracks, mediaviewer );
if( CopyToAction )
{
m_CopyToActionsMutex.Lock();
m_CopyToActions->Add( CopyToAction );
m_FileCount += CopyToAction->Count();
m_CopyToActionsMutex.Unlock();
if( !IsRunning() )
{
Run();
}
}
}
// -------------------------------------------------------------------------------- //
void guCopyToThread::AddAction( wxString * playlistpath, guMediaViewer * mediaviewer )
{
guCopyToAction * CopyToAction = new guCopyToAction( playlistpath, mediaviewer );
if( CopyToAction )
{
m_CopyToActionsMutex.Lock();
m_CopyToActions->Add( CopyToAction );
m_FileCount += CopyToAction->Count();
m_CopyToActionsMutex.Unlock();
if( !IsRunning() )
{
Run();
}
}
}
// -------------------------------------------------------------------------------- //
bool guCopyToThread::CopyFile( const wxString &from, const wxString &to )
{
bool RetVal = true;
//guLogMessage( wxT( "Copy %s =>> %s" ), from.c_str(), to.c_str() );
if( wxFileName::Mkdir( wxPathOnly( to ), 0777, wxPATH_MKDIR_FULL ) )
{
if( !wxCopyFile( from, to ) )
{
RetVal = false;
guLogError( wxT( "Could not copy the file '%s'" ), from.c_str() );
}
}
else
{
RetVal = false;
guLogError( wxT( "Could not create path for copy the file '%s'" ), from.c_str() );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guCopyToThread::TranscodeFile( const guTrack * track, const wxString &target, int format, int quality )
{
//guLogMessage( wxT( "guCopyToDeviceThread::TranscodeFile\nSource: '%s'\nTarget: '%s'\nFormat: %i\nQuality: %i" ),
// track->m_FileName.c_str(), target.c_str(), format, quality );
bool RetVal = false;
wxString OutFile = target + wxT( "." ) + guTranscodeFormatString( format );
if( wxFileName::Mkdir( wxPathOnly( target ), 0777, wxPATH_MKDIR_FULL ) )
{
// Some times gstreamer gives random errors processing some files. Specially ape format
// We retry 3 times
int RetryCount = 0;
while( RetryCount < 3 )
{
int FileSize = 0;
guTranscodeThread * TranscodeThread = new guTranscodeThread( track, OutFile.wchar_str(), format, quality );
if( TranscodeThread && TranscodeThread->IsOk() )
{
// TODO : Make a better aproach to be sure its running
Sleep( 1000 );
while( TranscodeThread->IsTranscoding() )
{
Sleep( 200 );
}
FileSize = guGetFileSize( OutFile );
m_SizeCounter += FileSize;
}
RetVal = TranscodeThread->IsOk();
RetryCount++;
if( FileSize )
break;
}
}
return RetVal;
}
#ifdef WITH_LIBGPOD_SUPPORT
// -------------------------------------------------------------------------------- //
bool guMoreCopyToIpodActions( guCopyToActionArray * actions )
{
if( actions->Count() > 1 )
{
int Count = actions->Count();
for( int Index = 1; Index < Count; Index++ )
{
guCopyToAction &CopyToAction = actions->Item( Index );
if( CopyToAction.Type() == guCOPYTO_ACTION_COPYTOIPOD )
return true;
}
}
return false;
}
#endif
// -------------------------------------------------------------------------------- //
void guCopyToThread::DoCopyToAction( guCopyToAction ©toaction )
{
int Count = copytoaction.Count();
wxString FileName;
wxString FilePattern;
wxString DestDir;
bool ActionIsCopy = true;
guMediaViewer * MediaViewer = copytoaction.GetMediaViewer();
FilePattern = copytoaction.Pattern();
//guLogMessage( wxT( "Using pattern '%s'" ), FilePattern.c_str() );
DestDir = copytoaction.DestDir();
for( int Index = 0; Index < Count; Index++ )
{
if( TestDestroy() )
break;
guTrack * CurTrack = copytoaction.Track( Index );
//
m_CurrentFile++;
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
event.SetInt( m_GaugeId );
event.SetExtraLong( m_FileCount );
wxPostEvent( m_MainFrame, event );
event.SetId( ID_STATUSBAR_GAUGE_UPDATE );
event.SetInt( m_GaugeId );
event.SetExtraLong( m_CurrentFile );
wxPostEvent( m_MainFrame, event );
if( CurTrack->m_Type == guTRACK_TYPE_RADIOSTATION )
continue;
bool Result;
FileName = wxEmptyString;
#ifdef WITH_LIBGPOD_SUPPORT
if( copytoaction.Type() == guCOPYTO_ACTION_COPYTOIPOD )
{
int FileSize = ( ( guMediaVieweriPodDevice * ) MediaViewer )->CopyTo( CurTrack, FileName );
if( FileSize == wxNOT_FOUND )
Result = false;
else
{
Result = true;
m_SizeCounter += FileSize;
// Add the file to the files to add list so the library update it when this job is done
m_FilesToAdd.Add( FileName );
}
}
else
#endif
{
FileName = guExpandTrackMacros( FilePattern, CurTrack, m_CurrentFile - 1 );
// TODO : Check target file system and filter the appropiate characters for every file system
// Replace all the special chars <>:" / \ | ? *
wxRegEx RegEx( wxT( "[<>:\\|?*]" ) );
RegEx.ReplaceAll( &FileName, wxT( "_" ) );
// The mtp devices may include a ':' in the mount folder
FileName = DestDir + FileName;
if( !CurTrack->m_Offset &&
( CurTrack->m_Type != guTRACK_TYPE_AUDIOCD ) &&
( copytoaction.Format() == guTRANSCODE_FORMAT_KEEP ) )
{
ActionIsCopy = true;
}
else
{
int FileFormat = guGetTranscodeFileFormat( CurTrack->m_FileName.Lower().AfterLast( wxT( '.' ) ) );
if( copytoaction.Type() == guCOPYTO_ACTION_COPYTO )
{
if( CurTrack->m_Offset &&
( copytoaction.Format() == guTRANSCODE_FORMAT_KEEP ) )
{
switch( FileFormat )
{
case guPORTABLEMEDIA_AUDIO_FORMAT_MP3 :
copytoaction.Format( guTRANSCODE_FORMAT_MP3 );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_AAC :
copytoaction.Format( guTRANSCODE_FORMAT_AAC );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_WMA :
copytoaction.Format( guTRANSCODE_FORMAT_WMA );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_OGG :
copytoaction.Format( guTRANSCODE_FORMAT_OGG );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_FLAC :
copytoaction.Format( guTRANSCODE_FORMAT_FLAC );
break;
default :
copytoaction.Format( guTRANSCODE_FORMAT_MP3 );
}
}
if( FileFormat == copytoaction.Format() )
{
if( !CurTrack->m_Offset && ( copytoaction.Quality() == guTRANSCODE_QUALITY_KEEP ) )
{
ActionIsCopy = true;
}
else
{
int FileBitrate = 0;
switch( FileFormat )
{
case guPORTABLEMEDIA_AUDIO_FORMAT_MP3 :
case guPORTABLEMEDIA_AUDIO_FORMAT_AAC :
case guPORTABLEMEDIA_AUDIO_FORMAT_WMA :
{
FileBitrate = guGetMp3QualityBitRate( copytoaction.Quality() );
break;
}
case guPORTABLEMEDIA_AUDIO_FORMAT_OGG :
{
FileBitrate = guGetOggQualityBitRate( copytoaction.Quality() );
break;
}
case guPORTABLEMEDIA_AUDIO_FORMAT_FLAC :
{
FileBitrate = 0;
break;
}
}
if( CurTrack->m_Offset || ( CurTrack->m_Bitrate > FileBitrate ) )
{
ActionIsCopy = false;
}
else
{
ActionIsCopy = true;
}
}
}
else
{
ActionIsCopy = false;
}
}
else
{
//guLogMessage( wxT( "AudioFormats: %08X %08X" ), MediaViewer->AudioFormats(), FileFormat );
// If the file is not supported then need to transcode it
if( CurTrack->m_Offset || !( MediaViewer->AudioFormats() & FileFormat ) )
{
//guLogMessage( wxT( "Its an unsupported format... Transcoding" ) );
ActionIsCopy = false;
if( copytoaction.Format() == guTRANSCODE_FORMAT_KEEP )
{
switch( FileFormat )
{
case guPORTABLEMEDIA_AUDIO_FORMAT_MP3 :
copytoaction.Format( guTRANSCODE_FORMAT_MP3 );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_AAC :
copytoaction.Format( guTRANSCODE_FORMAT_AAC );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_WMA :
copytoaction.Format( guTRANSCODE_FORMAT_WMA );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_OGG :
copytoaction.Format( guTRANSCODE_FORMAT_OGG );
break;
case guPORTABLEMEDIA_AUDIO_FORMAT_FLAC :
copytoaction.Format( guTRANSCODE_FORMAT_FLAC );
break;
default :
copytoaction.Format( guTRANSCODE_FORMAT_MP3 );
}
}
}
else // The file is supported
{
//guLogMessage( wxT( "Its a supported format" ) );
// The file is supported and we dont need to trasncode in all cases so copy the file
if( MediaViewer->TranscodeScope() != guPORTABLEMEDIA_TRANSCODE_SCOPE_ALWAYS )
{
ActionIsCopy = true;
}
else
{
//guLogMessage( wxT( "TranscodeFOrmat: %u FileFormat: %i" ), m_Device->TranscodeFormat(), FileFormat );
// The file is the same selected in the format so check if the bitrate is
if( MediaViewer->TranscodeFormat() == FileFormat )
{
if( MediaViewer->TranscodeQuality() != guTRANSCODE_QUALITY_KEEP )
{
int FileBitrate = 0;
switch( FileFormat )
{
case guPORTABLEMEDIA_AUDIO_FORMAT_MP3 :
case guPORTABLEMEDIA_AUDIO_FORMAT_AAC :
case guPORTABLEMEDIA_AUDIO_FORMAT_WMA :
{
FileBitrate = guGetMp3QualityBitRate( MediaViewer->TranscodeQuality() );
break;
}
case guPORTABLEMEDIA_AUDIO_FORMAT_OGG :
{
FileBitrate = guGetOggQualityBitRate( MediaViewer->TranscodeQuality() );
break;
}
case guPORTABLEMEDIA_AUDIO_FORMAT_FLAC :
{
FileBitrate = 0;
break;
}
}
if( CurTrack->m_Bitrate > FileBitrate )
{
ActionIsCopy = false;
}
else
{
ActionIsCopy = true;
}
}
else
{
ActionIsCopy = true;
}
}
else
{
ActionIsCopy = false;
}
}
}
}
}
if( ActionIsCopy )
{
FileName += wxT( '.' ) + CurTrack->m_FileName.Lower().AfterLast( wxT( '.' ) );
Result = CopyFile( CurTrack->m_FileName, FileName );
m_SizeCounter += CurTrack->m_FileSize;
}
else
{
Result = TranscodeFile( CurTrack, FileName, copytoaction.Format(), copytoaction.Quality() );
}
// Add the file to the files to add list so the library update it when this job is done
m_FilesToAdd.Add( FileName );
// If have cover assigned
if( CurTrack->m_CoverId )
{
if( copytoaction.Type() == guCOPYTO_ACTION_COPYTO )
{
guDbLibrary * Db = copytoaction.GetDb();
wxString CoverPath = Db->GetCoverPath( CurTrack->m_CoverId );
wxString NewCoverFile = wxPathOnly( FileName ) + wxT( "/" ) + CoverPath.AfterLast( wxT( '/' ) );
//guLogMessage( wxT( "COpying file %s" ), NewCoverFile.c_str() );
if( !wxFileExists( NewCoverFile ) )
{
if( !wxCopyFile( CoverPath, NewCoverFile ) )
{
guLogMessage( wxT( "Could not copy the cover %s" ), NewCoverFile.c_str() );
}
else
{
m_CoversToAdd.Add( NewCoverFile );
}
}
}
else
{
guMediaViewer * MediaViewer = CurTrack->m_MediaViewer;
guDbLibrary * Db = MediaViewer ? MediaViewer->GetDb() : NULL;
if( Db )
{
//
// If the device supports covers
//
int DevCoverFormats = copytoaction.CoverFormats();
if( DevCoverFormats ) // if has cover handling enabled
{
wxString CoverPath = Db->GetCoverPath( CurTrack->m_CoverId );
//guLogMessage( wxT( "Original Cover Path %i = '%s'" ), CurTrack->m_CoverId, CoverPath.c_str() );
wxImage * CoverImage = new wxImage( CoverPath );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
int DevCoverSize = copytoaction.CoverSize();
if( DevCoverSize && ( ( CoverImage->GetWidth() != DevCoverSize ) || ( CoverImage->GetHeight() != DevCoverSize ) ) )
{
CoverImage->Rescale( DevCoverSize, DevCoverSize, wxIMAGE_QUALITY_HIGH );
}
bool CoverAdded = false;
if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED )
{
if( !guTagSetPicture( FileName, CoverImage ) )
{
guLogMessage( wxT( "Couldnt set the picture to '%s'" ), FileName.c_str() );
}
}
wxString DevCoverName = copytoaction.CoverName();
if( DevCoverName.IsEmpty() )
{
DevCoverName = wxT( "cover" );
}
DevCoverName = wxPathOnly( FileName ) + wxT( "/" ) + DevCoverName;
if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_JPEG )
{
if( !wxFileExists( DevCoverName + wxT( ".jpg" ) ) )
{
if( !CoverImage->SaveFile( DevCoverName + wxT( ".jpg" ), wxBITMAP_TYPE_JPEG ) )
{
guLogError( wxT( "Could not copy the cover to '%s'" ), DevCoverName.c_str() );
}
else
{
m_CoversToAdd.Add( DevCoverName + wxT( ".jpg" ) );
CoverAdded = true;
}
}
}
if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_PNG )
{
if( !wxFileExists( DevCoverName + wxT( ".png" ) ) )
{
if( !CoverImage->SaveFile( DevCoverName + wxT( ".png" ), wxBITMAP_TYPE_PNG ) )
{
guLogError( wxT( "Could not copy the cover to '%s'" ), DevCoverName.c_str() );
}
else if( !CoverAdded )
{
m_CoversToAdd.Add( DevCoverName + wxT( ".png" ) );
CoverAdded = true;
}
}
}
if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_GIF )
{
if( !wxFileExists( DevCoverName + wxT( ".gif" ) ) )
{
if( !CoverImage->SaveFile( DevCoverName + wxT( ".gif" ), wxBITMAP_TYPE_GIF ) )
{
guLogError( wxT( "Could not copy the cover to '%s'" ), DevCoverName.c_str() );
}
else if( !CoverAdded )
{
m_CoversToAdd.Add( DevCoverName + wxT( ".gif" ) );
CoverAdded = true;
}
}
}
if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_BMP )
{
if( !wxFileExists( DevCoverName + wxT( ".bmp" ) ) )
{
if( !CoverImage->SaveFile( DevCoverName + wxT( ".bmp" ), wxBITMAP_TYPE_BMP ) )
{
guLogError( wxT( "Could not copy the cover to '%s'" ), DevCoverName.c_str() );
}
else if( !CoverAdded )
{
m_CoversToAdd.Add( DevCoverName + wxT( ".bmp" ) );
//CoverAdded = true;
}
}
}
}
delete CoverImage;
}
}
}
}
}
}
if( Result && copytoaction.MoveFiles() )
{
// Need to delete the old files
//CopyToAction.LibPanel()->DeleteTracks( CopyToAction.Tracks() );
m_DeleteTracks.Add( new guTrack( * CurTrack ) );
}
}
#ifdef WITH_LIBGPOD_SUPPORT
if( copytoaction.Type() == guCOPYTO_ACTION_COPYTOIPOD )
{
guPlaylistFile * PlayListFile = copytoaction.PlayListFile();
guIpodLibrary * IpodDb = ( guIpodLibrary * ) MediaViewer->GetDb();
if( PlayListFile )
{
//guLogMessage( wxT( "It was a playlist...") );
IpodDb->CreateiPodPlayList( PlayListFile->GetName(), m_FilesToAdd );
}
if( !guMoreCopyToIpodActions( m_CopyToActions ) )
{
IpodDb->iPodFlush();
MediaViewer->UpdateLibrary();
}
}
else
#endif
if( copytoaction.Type() == guCOPYTO_ACTION_COPYTODEVICE )
{
int Count;
// Update the files
guPortableMediaLibrary * PortableMediaDb = ( guPortableMediaLibrary * ) copytoaction.GetDb();
PortableMediaDb->AddFiles( m_FilesToAdd );
guPlaylistFile * PlayListFile = copytoaction.PlayListFile();
if( PlayListFile )
{
//guLogMessage( wxT( "Normal device and is from a playlist..." ) );
wxArrayInt TrackIds;
// The tracks just copied was part of a playlist we need to create too
Count = m_FilesToAdd.Count();
for( int Index = 0; Index < Count; Index++ )
{
int TrackId = PortableMediaDb->FindTrackFile( m_FilesToAdd[ Index ], NULL );
if( TrackId )
TrackIds.Add( TrackId );
}
if( TrackIds.Count() )
{
int PLId = PortableMediaDb->CreateStaticPlayList( PlayListFile->GetName(), TrackIds );
PortableMediaDb->UpdateStaticPlayListFile( PLId );
wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
wxPostEvent( m_MainFrame, evt );
}
}
if( MediaViewer )
{
guDbLibrary * Db = MediaViewer->GetDb();
if( Db )
{
// Update the covers
wxString DevCoverName = copytoaction.CoverName();
if( DevCoverName.IsEmpty() )
{
DevCoverName = wxT( "cover" );
}
DevCoverName += wxT( ".jpg" );
Count = m_CoversToAdd.Count();
for( int Index = 0; Index < Count; Index++ )
{
Db->UpdateImageFile( m_CoversToAdd[ Index ].ToUTF8(), DevCoverName.ToUTF8() );
}
}
}
}
if( MediaViewer )
{
if( m_DeleteTracks.Count() )
{
// Need to delete the old files
//CopyToAction.LibPanel()->DeleteTracks( &m_DeleteTracks );
MediaViewer->DeleteTracks( &m_DeleteTracks );
}
//copytoaction.GetMediaViewer()->LibraryUpdated();
//wxCommandEvent evt( wxEVT_MENU, ID_LIBRARY_UPDATED );
//wxPostEvent( MediaViewer, evt );
wxCommandEvent Event( wxEVT_MENU, MediaViewer->GetBaseCommand() + guCOLLECTION_ACTION_UPDATE_LIBRARY );
wxPostEvent( MediaViewer, Event );
}
else
{
if( m_DeleteTracks.Count() )
{
MediaViewer = m_MainFrame->GetDefaultMediaViewer();
MediaViewer->DeleteTracks( &m_DeleteTracks );
}
}
}
// -------------------------------------------------------------------------------- //
guCopyToThread::ExitCode guCopyToThread::Entry()
{
long IdleTime = wxNOT_FOUND;
long TimeCounter = wxNOT_FOUND;
unsigned int FileCounter = 0;
while( !TestDestroy() )
{
if( m_CopyToActions->Count() )
{
IdleTime = wxNOT_FOUND;
if( TimeCounter == wxNOT_FOUND )
{
TimeCounter = wxGetLocalTime();
m_SizeCounter = 0;
FileCounter = 0;
}
m_FilesToAdd.Empty();
m_DeleteTracks.Empty();
m_CoversToAdd.Empty();
m_CopyToActionsMutex.Lock();
guCopyToAction &CopyToAction = m_CopyToActions->Item( 0 );
m_CopyToActionsMutex.Unlock();
DoCopyToAction( CopyToAction );
FileCounter += CopyToAction.Count();
m_CopyToActionsMutex.Lock();
m_CopyToActions->RemoveAt( 0 );
m_CopyToActionsMutex.Unlock();
// If was the last items in the list we send the notification
if( !m_CopyToActions->Count() )
{
// Send notification that the job finished
guDBusNotify * NotifySrv = m_MainFrame->GetNotifyObject();
if( NotifySrv )
{
TimeCounter = wxGetLocalTime() - TimeCounter;
wxString FinishMsg = wxString::Format( _( "Copied %u files (%s)\nin %s seconds" ),
FileCounter,
SizeToString( m_SizeCounter ).c_str(),
LenToString( TimeCounter * 1000 ).c_str() );
wxImage IconImg = guImage( guIMAGE_INDEX_guayadeque );
NotifySrv->Notify( wxEmptyString, _( "Finished copying files" ), FinishMsg, &IconImg );
}
//
TimeCounter = wxNOT_FOUND;
}
}
else
{
if( IdleTime == wxNOT_FOUND )
{
IdleTime = wxGetLocalTime();
m_FileCount = 0;
m_CurrentFile = 0;
}
// we have been waiting in idle for more than 10 seconds now
if( wxGetLocalTime() - IdleTime > 10 )
{
break;
}
Sleep( 1000 );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 36,347
|
C++
|
.cpp
| 823
| 27.414338
| 175
| 0.436274
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,567
|
LastFM.cpp
|
anonbeat_guayadeque/src/info/lastfm/LastFM.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "LastFM.h"
#include "Config.h"
#include "DbCache.h"
#include "Utils.h"
#include "Http.h"
#include <wx/arrimpl.cpp>
#include <wx/sstream.h>
#include <wx/xml/xml.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guAlbumInfoArray )
WX_DEFINE_OBJARRAY( guTopTrackInfoArray )
WX_DEFINE_OBJARRAY( guSimilarArtistInfoArray )
WX_DEFINE_OBJARRAY( guSimilarTrackInfoArray )
WX_DEFINE_OBJARRAY( guEventInfoArray )
// -------------------------------------------------------------------------------- //
// guLastFMRequest
// -------------------------------------------------------------------------------- //
guLastFMRequest::guLastFMRequest()
{
}
// -------------------------------------------------------------------------------- //
guLastFMRequest::~guLastFMRequest()
{
}
// -------------------------------------------------------------------------------- //
void guLastFMRequest::AddArgument( const wxString &ArgName, const wxString &ArgValue, bool Filter )
{
if( Filter )
{
AddArgument( guURLEncode( ArgName ), guURLEncode( ArgValue ) );
}
else
{
AddArgument( ArgName, ArgValue );
}
}
// -------------------------------------------------------------------------------- //
void guLastFMRequest::AddArgument( const wxString &ArgName, const wxString &ArgValue )
{
m_Args.Add( ArgName + wxT( '=' ) + ArgValue );
}
// -------------------------------------------------------------------------------- //
void guLastFMRequest::SetMethod( const wxString &MethodName )
{
//Method = MethodName;
m_Args.Add( wxT( "method=" ) + MethodName );
}
// -------------------------------------------------------------------------------- //
wxString guLastFMRequest::GetSign()
{
wxSortedArrayString Params;
wxString SignStr = wxEmptyString;
guMD5 md5;
int Count = m_Args.Count();
for( int Index = 0; Index < Count; Index++ )
{
SignStr += m_Args[ Index ].BeforeFirst( '=' );
SignStr += m_Args[ Index ].AfterFirst( '=' );
}
SignStr += LASTFM_SHARED_SECRET;
return md5.MD5( SignStr );
}
// -------------------------------------------------------------------------------- //
wxString guLastFMRequest::DoRequest( const bool AddSign, const bool IsGetAction )
{
wxString RetVal = wxEmptyString;
guHttp Http;
char * Buffer = NULL;
wxString UrlStr = wxEmptyString; // = LASTFM_API_ROOT;
// TODO : Add a check to check if there was a recent request to last fm.
// LastFM can ban apps that do too much requests per second.
//
// TODO : Add a LastFM query cache where stores the queries and respective responses
//
int Count = m_Args.Count();
for( int Index = 0; Index < Count; Index++ )
{
UrlStr += ( Index ? wxT( "&" ) : wxT( "?" ) ) + m_Args[ Index ];
}
if( AddSign )
UrlStr += wxT( "&api_sig=" ) + GetSign();
if( IsGetAction )
{
UrlStr = LASTFM_API_ROOT + UrlStr;
guDbCache * DbCache = guDbCache::GetDbCache();
if( DbCache )
{
RetVal = DbCache->GetContent( UrlStr );
//guLogMessage( wxT( "DbCache::GetContent:\n%s" ), RetVal.Mid( 0, 100 ).c_str() );
}
if( RetVal.IsEmpty() )
{
// Only with a UserAgent is accepted the Charset requested
Http.AddHeader( wxT( "User-Agent" ), guDEFAULT_BROWSER_USER_AGENT );
Http.AddHeader( wxT( "Accept" ), wxT( "text/html" ) );
Http.AddHeader( wxT( "Accept-Charset" ), wxT( "utf-8" ) );
//guLogMessage( wxT( "LastFM.DoRequest %s\n" ), UrlStr.c_str() );
Http.Get( Buffer, UrlStr );
if( Buffer )
{
RetVal = wxString( Buffer, wxConvUTF8 );
if( RetVal.IsEmpty() )
{
RetVal = wxString( Buffer, wxConvISO8859_1 );
if( RetVal.IsEmpty() )
RetVal = wxString( Buffer, wxConvLibc );
}
if( !RetVal.IsEmpty() )
{
DbCache->SetContent( UrlStr, RetVal, guDBCACHE_TYPE_LASTFM );
}
free( Buffer );
}
}
}
else
{
//guLogMessage( wxT( "LastFM.DoRequest POST %s\n" ), UrlStr.c_str() );
Http.Post( UrlStr.Mid( 1 ).char_str(), UrlStr.Length() - 1, LASTFM_API_ROOT );
}
// else
// {
// guLogError( wxT( "DoRequest() : %s\nError: (%d) %s\nHeaders: %s\nBody: %s" ),
// UrlStr.c_str(),
// http.GetResponseCode(),
// http.GetDetailedErrorString().c_str(),
// http.GetResponseHeader().c_str(),
// http.GetResponseBody().c_str() );
// }
//guLogMessage( wxT( "%s" ), RetVal.c_str() );
return RetVal;
}
// -------------------------------------------------------------------------------- //
// guLastFM
// -------------------------------------------------------------------------------- //
guLastFM::guLastFM()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
m_UserName = Config->ReadStr( CONFIG_KEY_LASTFM_USERNAME, wxEmptyString, CONFIG_PATH_LASTFM );
m_Password = Config->ReadStr( CONFIG_KEY_LASTFM_PASSWORD, wxEmptyString, CONFIG_PATH_LASTFM );
m_AuthSession = Config->ReadStr( CONFIG_KEY_LASTFM_SESSIONKEY, wxEmptyString, CONFIG_PATH_LASTFM );
m_Language = Config->ReadStr( CONFIG_KEY_LASTFM_LANGUAGE, wxEmptyString, CONFIG_PATH_LASTFM );
}
m_ErrorCode = 0;
//DoAuthentication();
}
// -------------------------------------------------------------------------------- //
guLastFM::~guLastFM()
{
}
// -------------------------------------------------------------------------------- //
wxString guLastFM::GetAuthURL()
{
return LASTFM_AUTH_ROOT wxT( "?api_key=" ) LASTFM_API_KEY wxT( "&token=" ) + m_AuthToken;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::IsOk()
{
return m_ErrorCode == wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
wxString guLastFM::GetAuthSession()
{
if( m_AuthSession.IsEmpty() )
{
m_AuthToken = AuthGetToken();
if( IsOk() )
{
// Get Authorization From User in Navigator
// Get Session
m_AuthSession = AuthGetSession();
}
}
return m_AuthSession;
}
// -------------------------------------------------------------------------------- //
wxString guLastFM::AuthGetToken()
{
guLastFMRequest * Req = new guLastFMRequest();
wxString Res;
wxString Status;
wxString Token = wxEmptyString;
Req->SetMethod( wxT( "auth.gettoken" ) );
Req->AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Res = Req->DoRequest();
// printf( "getToken() : " ); printf( Res.char_str() ); printf( "\n" );
//<?xml version="1.0" encoding="utf-8"?>
//<lfm status="ok">
//<token>6fe1b405832e101e73a70d0d6c1832f6</token></lfm>
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "token" ) )
{
m_ErrorCode = 0;
Token = XmlNode->GetNodeContent();
//printf( Token.char_str() ); printf( "\n" );
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
//
delete Req;
return Token;
}
// -------------------------------------------------------------------------------- //
wxString guLastFM::AuthGetSession()
{
guLastFMRequest * Req = new guLastFMRequest();
wxString Res;
wxString Status;
wxString Key = wxEmptyString;
Req->SetMethod( wxT( "auth.getsession" ) );
Req->AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req->AddArgument( wxT( "token" ), m_AuthToken );
Res = Req->DoRequest();
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "session" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "key" ) )
{
m_ErrorCode = 0;
Key = XmlNode->GetNodeContent();
//printf( Token.char_str() ); printf( "\n" );
break;
}
XmlNode = XmlNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
//
delete Req;
return Key;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::DoAuthentication()
{
m_AuthToken = AuthGetToken();
if( m_ErrorCode == 0 )
{
//printf( GetAuthURL().char_str() ); printf( "\n" );
m_AuthSession = AuthGetSession();
//printf( "AuthSession: " ); printf( AuthSession.char_str() ); printf( "\n" );
if( m_AuthSession.IsEmpty() )
guLogError( wxT( "LastFM::DoAuthentication ErrorCode: %d " ), m_ErrorCode );
else
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::AlbumAddTags( const wxString &Artist, const wxString &Album, const wxString &Tags )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
Req.SetMethod( wxT( "album.addtags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "album" ), Album, true );
Req.AddArgument( wxT( "tags" ), Tags, true );
Res = Req.DoRequest( true, false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
guAlbumInfo guLastFM::AlbumGetInfo( const wxString &Artist, const wxString &Album )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guAlbumInfo RetVal;
wxString ItemName;
wxString ImageSize;
wxString Tags = wxEmptyString;
Req.SetMethod( wxT( "album.getinfo" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "album" ), Album, true );
if( !m_Language.IsEmpty() )
{
Req.AddArgument( wxT( "lang" ), m_Language );
}
Res = Req.DoRequest( false );
//printf( "====\n" ); printf( Res.char_str() ); printf( "====\n" );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "album" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
ItemName = XmlNode->GetName();
if( ItemName == wxT( "name" ) )
{
RetVal.m_Name = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "artist" ) )
{
RetVal.m_Artist = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "releasedate" ) )
{
RetVal.m_ReleaseDate = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "url" ) )
{
RetVal.m_Url = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "image" ) )
{
XmlNode->GetAttribute( wxT( "size" ), &ImageSize );
//printf( "IMAGESIZE: " ); printf( ImageSize.char_str() ); printf( "\n" );
if( ImageSize == wxT( "large" ) && RetVal.m_ImageLink.IsEmpty() )
{
RetVal.m_ImageLink = XmlNode->GetNodeContent();
}
else if( ImageSize == wxT( "extralarge" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
RetVal.m_ImageLink = XmlNode->GetNodeContent();
}
else if( ImageSize == wxT( "mega" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
RetVal.m_ImageLink = XmlNode->GetNodeContent();
}
}
else if( ItemName == wxT( "toptags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "tag" ) )
{
Tags += XmlSubNode->GetChildren()->GetNodeContent() + wxT( "," );
}
XmlSubNode = XmlSubNode->GetNext();
}
RetVal.m_Tags = Tags.RemoveLast( 1 );
}
XmlNode = XmlNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guLastFM::AlbumGetTags( const wxString &Artist, const wxString &Album )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxArrayString RetVal;
Req.SetMethod( wxT( "album.gettags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "album" ), Album, true );
Res = Req.DoRequest();
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "tags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "tag" ) )
{
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name" ) )
{
RetVal.Add( XmlNode->GetContent() );
break;
}
XmlNode = XmlNode->GetNext();
}
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::AlbumRemoveTag( const wxString &Artist, const wxString &Album, const wxString &Tag )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
Req.SetMethod( wxT( "album.removetag" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "album" ), Album, true );
Req.AddArgument( wxT( "tag" ), Tag, true );
Res = Req.DoRequest( true, false ); // Append Sign and Do as Post
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::ArtistAddTags( const wxString &Artist, const wxString &Tags )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
Req.SetMethod( wxT( "album.addtags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "tags" ), Tags, true );
Res = Req.DoRequest( true, false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
guArtistInfo guLastFM::ArtistGetInfo( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guArtistInfo RetVal;
wxString ItemName;
wxString ImageSize;
Req.SetMethod( wxT( "artist.getinfo" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
if( !m_Language.IsEmpty() )
{
Req.AddArgument( wxT( "lang" ), m_Language );
}
Res = Req.DoRequest( false );
//guLogMessage( wxT( "ArtistGetInfo:\n%s" ), Res.c_str() );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
ItemName = XmlNode->GetName();
if( ItemName == wxT( "name" ) )
{
RetVal.m_Name = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "url" ) )
{
RetVal.m_Url = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "image" ) )
{
XmlNode->GetAttribute( wxT( "size" ), &ImageSize );
if( ImageSize == wxT( "large" ) && RetVal.m_ImageLink.IsEmpty() )
{
RetVal.m_ImageLink = XmlNode->GetNodeContent();
}
else if( ImageSize == wxT( "extralarge" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
RetVal.m_ImageLink = XmlNode->GetNodeContent();
}
}
else if( ItemName == wxT( "tags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "tag" ) )
{
RetVal.m_Tags.Add( XmlSubNode->GetChildren()->GetNodeContent() );
}
XmlSubNode = XmlSubNode->GetNext();
}
}
else if( ItemName == wxT( "bio" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "summary" ) )
{
RetVal.m_BioSummary = XmlSubNode->GetNodeContent();
} else if( XmlSubNode->GetName() == wxT( "content" ) )
{
RetVal.m_BioContent = XmlSubNode->GetNodeContent();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
XmlNode = XmlNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
guSimilarArtistInfoArray guLastFM::ArtistGetSimilar( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guSimilarArtistInfoArray RetVal;
wxString ItemName;
wxString ImageSize;
wxString Tags = wxEmptyString;
Req.SetMethod( wxT( "artist.getsimilar" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest( false ); // Does not require signature
// <lfm status="ok">
// <similarartists artist="Cher">
// <artist>
// <name>Tina Turner</name>
// <mbid>9072df14-b61e-42e2-b4f4-6bbb7fdb5586</mbid>
// <match>100</match>
// <url>www.last.fm/music/Tina+Turner</url>
// <image size="small">http://userserve-ak.last.fm/serve/34/72791.jpg</image>
// <image size="medium">http://userserve-ak.last.fm/serve/64/72791.jpg</image>
// <image size="large">http://userserve-ak.last.fm/serve/126/72791.jpg</image>
// <streamable>1</streamable>
// </artist>
// ...
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "similarartists" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode && XmlNode->GetName() == wxT( "artist" ) )
{
guSimilarArtistInfo * CurItem = new guSimilarArtistInfo();
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
ItemName = XmlSubNode->GetName();
//guLogMessage( wxT( "%s : %s" ), ItemName.c_str(), XmlSubNode->GetNodeContent().c_str() );
if( ItemName == wxT( "name" ) )
{
CurItem->m_Name = XmlSubNode->GetNodeContent();
}
else if( ItemName == wxT( "match" ) )
{
CurItem->m_Match = XmlSubNode->GetNodeContent();
}
else if( ItemName == wxT( "url" ) )
{
CurItem->m_Url = XmlSubNode->GetNodeContent();
}
else if( ItemName == wxT( "image" ) )
{
XmlSubNode->GetAttribute( wxT( "size" ), &ImageSize );
if( ImageSize == wxT( "large" ) && CurItem->m_ImageLink.IsEmpty() )
{
CurItem->m_ImageLink = XmlSubNode->GetNodeContent();
}
else if( ImageSize == wxT( "extralarge" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
CurItem->m_ImageLink = XmlSubNode->GetNodeContent();
}
}
XmlSubNode = XmlSubNode->GetNext();
}
RetVal.Add( CurItem );
XmlNode = XmlNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guLastFM::ArtistGetTags( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxArrayString RetVal;
Req.SetMethod( wxT( "artist.gettags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest();
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "tags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "tag" ) )
{
RetVal.Add( XmlSubNode->GetChildren()->GetContent() );
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
guAlbumInfoArray guLastFM::ArtistGetTopAlbums( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxString ItemName;
wxString ImageSize;
guAlbumInfoArray RetVal;
guAlbumInfo * CurItem;
Req.SetMethod( wxT( "artist.gettopalbums" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "topalbums" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "album" ) )
{
CurItem = new guAlbumInfo();
if( CurItem )
{
CurItem->m_Artist = Artist;
XmlSubNode->GetAttribute( wxT( "rank" ), &CurItem->m_Rank );
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
ItemName = XmlNode->GetName();
if( ItemName == wxT( "name" ) )
{
CurItem->m_Name = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "url" ) )
{
CurItem->m_Url = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "image" ) )
{
XmlNode->GetAttribute( wxT( "size" ), &ImageSize );
//printf( "IMAGESIZE: " ); printf( ImageSize.char_str() ); printf( "\n" );
if( ImageSize == wxT( "large" ) && CurItem->m_ImageLink.IsEmpty() )
{
CurItem->m_ImageLink = XmlNode->GetNodeContent();
}
else if( ImageSize == wxT( "extralarge" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
CurItem->m_ImageLink = XmlNode->GetNodeContent();
}
}
XmlNode = XmlNode->GetNext();
}
RetVal.Add( CurItem );
}
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guLastFM::ArtistGetTopTags( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxArrayString RetVal;
Req.SetMethod( wxT( "artist.gettoptags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "toptags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name" ) )
{
RetVal.Add( XmlNode->GetNodeContent() );
break;
}
XmlNode = XmlNode->GetNext();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void GetArtistTopTrackArtist( wxXmlNode * xmlnode, guTopTrackInfo * toptrack )
{
// <name>Modern Talking</name>
// <mbid>98913495-8867-43b3-aa8d-db88ee4d4cdc</mbid>
// <url>http://www.last.fm/music/Modern+Talking</url>
while( xmlnode )
{
if( xmlnode->GetName() == wxT( "name" ) )
{
toptrack->m_ArtistName = xmlnode->GetNodeContent();
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void GetArtistTopTrack( wxXmlNode * xmlnode, guTopTrackInfo * toptrack )
{
// <name>Brother Louie</name>
// <playcount>34061</playcount>
// <listeners>11721</listeners>
// <mbid/>
// <url>http://www.last.fm/music/Modern+Talking/_/Brother+Louie</url>
// <streamable fulltrack="0">1</streamable>
// <artist>
// <name>Modern Talking</name>
// <mbid>98913495-8867-43b3-aa8d-db88ee4d4cdc</mbid>
// <url>http://www.last.fm/music/Modern+Talking</url>
// </artist>
// <image size="small">http://userserve-ak.last.fm/serve/34s/31763881.jpg</image>
// <image size="medium">http://userserve-ak.last.fm/serve/64s/31763881.jpg</image>
// <image size="large">http://userserve-ak.last.fm/serve/126/31763881.jpg</image>
// <image size="extralarge">http://userserve-ak.last.fm/serve/300x300/31763881.jpg</image>
while( xmlnode )
{
if( xmlnode->GetName() == wxT( "name" ) )
{
toptrack->m_TrackName = xmlnode->GetNodeContent();
}
else if( xmlnode->GetName() == wxT( "playcount" ) )
{
long PlayCount = 0;
xmlnode->GetNodeContent().ToLong( &PlayCount );
toptrack->m_PlayCount = PlayCount;
}
else if( xmlnode->GetName() == wxT( "listeners" ) )
{
long Listeners = 0;
xmlnode->GetNodeContent().ToLong( &Listeners );
toptrack->m_Listeners = Listeners;
}
else if( xmlnode->GetName() == wxT( "artist" ) )
{
GetArtistTopTrackArtist( xmlnode->GetChildren(), toptrack );
}
else if( xmlnode->GetName() == wxT( "url" ) )
{
toptrack->m_Url = xmlnode->GetNodeContent();
}
else if( xmlnode->GetName() == wxT( "image" ) )
{
wxString ImgSize;
xmlnode->GetAttribute( wxT( "size" ), &ImgSize );
if( ImgSize == wxT( "large" ) && toptrack->m_ImageLink.IsEmpty() )
{
toptrack->m_ImageLink = xmlnode->GetNodeContent();
}
else if( ImgSize == wxT( "extralarge" ) && !xmlnode->GetNodeContent().IsEmpty() )
{
toptrack->m_ImageLink = xmlnode->GetNodeContent();
}
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void GetArtistTopTracks( wxXmlNode * xmlnode, guTopTrackInfoArray * toptracks )
{
while( xmlnode )
{
if( xmlnode->GetName() == wxT( "track" ) )
{
guTopTrackInfo TopTrackInfo;
GetArtistTopTrack( xmlnode->GetChildren(), &TopTrackInfo );
toptracks->Add( TopTrackInfo );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
guTopTrackInfoArray guLastFM::ArtistGetTopTracks( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guTopTrackInfoArray RetVal;
Req.SetMethod( wxT( "artist.gettoptracks" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
// <lfm status="ok">
// <toptracks artist="Modern Talking">
// <track rank="1">
// <name>Brother Louie</name>
// <playcount>34061</playcount>
// <listeners>11721</listeners>
// <mbid/>
// <url>http://www.last.fm/music/Modern+Talking/_/Brother+Louie</url>
// <streamable fulltrack="0">1</streamable>
// <artist>
// <name>Modern Talking</name>
// <mbid>98913495-8867-43b3-aa8d-db88ee4d4cdc</mbid>
// <url>http://www.last.fm/music/Modern+Talking</url>
// </artist>
// <image size="small">http://userserve-ak.last.fm/serve/34s/31763881.jpg</image>
// <image size="medium">http://userserve-ak.last.fm/serve/64s/31763881.jpg</image>
// <image size="large">http://userserve-ak.last.fm/serve/126/31763881.jpg</image>
// <image size="extralarge">http://userserve-ak.last.fm/serve/300x300/31763881.jpg</image>
// </track>
// <track rank="2">
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "toptracks" ) )
{
GetArtistTopTracks( XmlNode->GetChildren(), &RetVal );
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEventArtists( wxXmlNode * XmlNode, wxArrayString * Artists )
{
while( XmlNode && XmlNode->GetName() == wxT( "artist" ) )
{
Artists->Add( XmlNode->GetNodeContent() );
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEventVenueLocationGeo( wxXmlNode * XmlNode, guEventInfo * Event )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "geo:lat" ) )
{
Event->m_LocationGeoLat = XmlNode->GetNodeContent();
}
if( XmlNode->GetName() == wxT( "geo:long" ) )
{
Event->m_LocationGeoLong = XmlNode->GetNodeContent();
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEventVenueLocation( wxXmlNode * XmlNode, guEventInfo * Event )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "city" ) )
{
Event->m_LocationCity = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "country" ) )
{
Event->m_LocationCountry = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "street" ) )
{
Event->m_LocationStreet = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "postalcode" ) )
{
Event->m_LocationZipCode = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "geo:point" ) )
{
ReadXmlArtistEventVenueLocationGeo( XmlNode->GetChildren(), Event );
}
else if( XmlNode->GetName() == wxT( "timezone" ) )
{
Event->m_LocationTimeZone = XmlNode->GetNodeContent();
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEventVenue( wxXmlNode * XmlNode, guEventInfo * Event )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name" ) )
{
Event->m_LocationName = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "location" ) )
{
ReadXmlArtistEventVenueLocation( XmlNode->GetChildren(), Event );
}
else if( XmlNode->GetName() == wxT( "url" ) )
{
Event->m_LocationLink = XmlNode->GetNodeContent();
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEvent( wxXmlNode * XmlNode, guEventInfo * Event )
{
while( XmlNode )
{
//guLogMessage( wxT( "%s = %s" ), XmlNode->GetName().c_str(), XmlNode->GetNodeContent().c_str() );
if( XmlNode->GetName() == wxT( "id" ) )
{
long Id;
XmlNode->GetNodeContent().ToLong( &Id );
Event->m_Id = Id;
}
else if( XmlNode->GetName() == wxT( "title" ) )
{
Event->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "artists" ) )
{
ReadXmlArtistEventArtists( XmlNode->GetChildren(), &Event->m_Artists );
}
else if( XmlNode->GetName() == wxT( "venue" ) )
{
ReadXmlArtistEventVenue( XmlNode->GetChildren(), Event );
}
else if( XmlNode->GetName() == wxT( "startDate" ) )
{
Event->m_Date = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "startTime" ) )
{
Event->m_Time = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "description" ) )
{
Event->m_Description = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "description" ) )
{
Event->m_Description = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "image" ) )
{
wxString LastUrl = Event->m_ImageLink;
Event->m_ImageLink = XmlNode->GetNodeContent();
if( Event->m_ImageLink.IsEmpty() )
Event->m_ImageLink = LastUrl;
}
else if( XmlNode->GetName() == wxT( "url" ) )
{
Event->m_Url = XmlNode->GetNodeContent();
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlArtistEvents( wxXmlNode * XmlNode, guEventInfoArray * Events )
{
while( XmlNode && XmlNode->GetName() == wxT( "event" ) )
{
guEventInfo * Event = new guEventInfo;
ReadXmlArtistEvent( XmlNode->GetChildren(), Event );
Events->Add( Event );
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
guEventInfoArray guLastFM::ArtistGetEvents( const wxString &Artist )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guEventInfoArray RetVal;
Req.SetMethod( wxT( "artist.getEvents" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "events" ) )
{
ReadXmlArtistEvents( XmlNode->GetChildren(), &RetVal );
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
guTrackInfo guLastFM::TrackGetInfo( const wxString &Artist, const wxString &Track )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
guTrackInfo RetVal;
wxString ItemName;
Req.SetMethod( wxT( "track.getinfo" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "track" ), Track, true );
if( !m_Language.IsEmpty() )
{
Req.AddArgument( wxT( "lang" ), m_Language );
}
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "track" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
ItemName = XmlNode->GetName();
if( ItemName == wxT( "name" ) )
{
RetVal.m_TrackName = XmlNode->GetContent();
}
else if( ItemName == wxT( "url" ) )
{
RetVal.m_Url = XmlNode->GetContent();
}
else if( ItemName == wxT( "toptags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode && XmlSubNode->GetName() == wxT( "tag" ) )
{
// Get Tag Property
wxXmlNode * TagNode = XmlSubNode->GetChildren();
while( TagNode )
{
if( TagNode->GetName() == wxT( "name" ) )
{
RetVal.m_TopTags.Add( TagNode->GetContent() );
break;
}
TagNode = TagNode->GetNext();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
else if( ItemName == wxT( "wiky" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "content" ) )
{
RetVal.m_Content = XmlSubNode->GetContent();
}
else if( XmlSubNode->GetName() == wxT( "summary" ) )
{
RetVal.m_Summary = XmlSubNode->GetContent();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
guSimilarTrackInfoArray guLastFM::TrackGetSimilar( const wxString &Artist, const wxString &Track )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxString ImageSize;
guSimilarTrackInfoArray RetVal;
Req.SetMethod( wxT( "track.getsimilar" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "track" ), Track, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "similartracks" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode && XmlSubNode->GetName() == wxT( "track" ) )
{
guSimilarTrackInfo * CurItem = new guSimilarTrackInfo();
if( CurItem )
{
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
wxString ItemName = XmlNode->GetName();
//wxLogWarning( wxT( "XmlNode: %s" ), ItemName.c_str() );
if( ItemName == wxT( "name" ) )
{
CurItem->m_TrackName = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "match" ) )
{
CurItem->m_Match = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "url" ) )
{
CurItem->m_Url = XmlNode->GetNodeContent();
}
else if( ItemName == wxT( "artist" ) )
{
wxXmlNode * ArtistNode = XmlNode->GetChildren();
while( ArtistNode )
{
//wxLogWarning( wxT( "ArtistXmlNode: %s" ), ArtistNode->GetName().c_str() );
if( ArtistNode->GetName() == wxT( "name" ) )
{
CurItem->m_ArtistName = ArtistNode->GetNodeContent();
break;
}
ArtistNode = ArtistNode->GetNext();
}
}
else if( ItemName == wxT( "image" ) )
{
XmlNode->GetAttribute( wxT( "size" ), &ImageSize );
if( ImageSize == wxT( "large" ) && CurItem->m_ImageLink.IsEmpty() )
{
CurItem->m_ImageLink = XmlNode->GetNodeContent();
}
else if( ImageSize == wxT( "extralarge" ) && !XmlNode->GetNodeContent().IsEmpty() )
{
CurItem->m_ImageLink = XmlNode->GetNodeContent();
}
}
XmlNode = XmlNode->GetNext();
}
RetVal.Add( CurItem );
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guLastFM::TrackGetTags( const wxString &Artist, const wxString &Album )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxArrayString RetVal;
Req.SetMethod( wxT( "track.gettags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "album" ), Album, true );
Res = Req.DoRequest();
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "tags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode && XmlSubNode->GetName() == wxT( "tag" ) )
{
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name" ) )
{
RetVal.Add( XmlNode->GetContent() );
break;
}
XmlNode = XmlNode->GetNext();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guLastFM::TrackGetTopTags( const wxString &Artist, const wxString &Track )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxArrayString RetVal;
Req.SetMethod( wxT( "track.gettoptags" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "track" ), Track, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "toptags" ) )
{
wxXmlNode * XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode && XmlSubNode->GetName() == wxT( "tag" ) )
{
XmlNode = XmlSubNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name" ) )
{
RetVal.Add( XmlNode->GetNodeContent() );
break;
}
XmlNode = XmlNode->GetNext();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::TrackRemoveTag( const wxString &Artist, const wxString &Track, const wxString &Tag )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
Req.SetMethod( wxT( "track.removetag" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "sk" ), GetAuthSession() );
Req.AddArgument( wxT( "artist" ), Artist, true );
Req.AddArgument( wxT( "track" ), Track, true );
Req.AddArgument( wxT( "tag" ), Tag, true );
Res = Req.DoRequest( true, false ); // Append Sign and Do as Post
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
//printf( XmlNode->GetName().char_str() ); printf( "\n" );
XmlNode->GetAttribute( wxT( "status" ), &Status );
//printf( Status.char_str() ); printf( "\n" );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::TrackLove( const wxString &artist, const wxString &title )
{
guLastFMRequest Req; // = guLastFMRequest();
wxString Res;
wxString Status;
wxString ItemName;
Req.SetMethod( wxT( "track.love" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), artist, true );
Req.AddArgument( wxT( "track" ), title, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
XmlNode->GetAttribute( wxT( "status" ), &Status );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guLastFM::TrackBan( const wxString &artist, const wxString &title )
{
guLastFMRequest Req;
wxString Res;
wxString Status;
wxString ItemName;
Req.SetMethod( wxT( "track.ban" ) );
Req.AddArgument( wxT( "api_key" ), LASTFM_API_KEY );
Req.AddArgument( wxT( "artist" ), artist, true );
Req.AddArgument( wxT( "track" ), title, true );
Res = Req.DoRequest( false );
m_ErrorCode = wxNOT_FOUND;
if( Res.Length() )
{
wxStringInputStream ins( Res );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode )
{
if( XmlNode->GetName() == wxT( "lfm" ) )
{
XmlNode->GetAttribute( wxT( "status" ), &Status );
if( Status == wxT( "ok" ) )
{
return true;
}
else if( Status == wxT( "failed" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode && XmlNode->GetName() == wxT( "error" ) )
{
XmlNode->GetAttribute( wxT( "code" ), &Status );
Status.ToLong( &m_ErrorCode );
}
}
}
}
}
return false;
}
}
// -------------------------------------------------------------------------------- //
| 75,853
|
C++
|
.cpp
| 1,832
| 26.923581
| 127
| 0.410867
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,568
|
SmartMode.cpp
|
anonbeat_guayadeque/src/info/smartmode/SmartMode.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "SmartMode.h"
#include "EventCommandIds.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "PlayListAppend.h"
namespace Guayadeque {
#define guSMARTMODE_MIN_TRACK_MATCH 0.1
#define guSMARTMODE_MIN_ARTIST_MATCH 0.2
// -------------------------------------------------------------------------------- //
guSmartModeThread::guSmartModeThread( guDbLibrary * db, wxEvtHandler * owner,
const wxString &artistname, const wxString &trackname,
wxArrayInt * smartaddedtracks, wxArrayString * smartaddedartists,
const int maxtracks, const int maxartists,
const uint tracklimit, const int limittype,
const int filterallow, const int filterdeny,
const int gaugeid ) :
wxThread()
{
//guLogMessage( wxT( "guSmartModeThread::guSmartModeThread" ) );
m_Db = db;
m_Owner = owner;
m_ArtistName = wxString( artistname.c_str() );
m_TrackName = wxString( trackname.c_str() );
m_SmartAddedTracks = smartaddedtracks;
m_SmartAddedArtists = smartaddedartists;
m_MaxSmartTracksList = maxtracks;
m_MaxSmartArtistsList = maxartists;
m_FilterAllowPlayList = filterallow;
m_FilterDenyPlayList = filterdeny;
m_GaugeId = gaugeid;
m_LimitType = limittype;
switch( limittype )
{
case guSMARTMODE_TRACK_LIMIT_TIME_MINUTES :
m_TrackLimit = tracklimit * 60000;
break;
case guSMARTMODE_TRACK_LIMIT_TIME_HOURS :
m_TrackLimit = ( tracklimit * 60 * 60000 );
break;
case guSMARTMODE_TRACK_LIMIT_SIZE_MB :
m_TrackLimit = ( tracklimit * 1024 * 1024 );
break;
case guSMARTMODE_TRACK_LIMIT_SIZE_GB :
m_TrackLimit = ( tracklimit * 1024 * 1024 * 1024 );
break;
//case guSMARTMODE_TRACK_LIMIT_TRACKS :
default :
m_TrackLimit = tracklimit;
m_LimitType = guSMARTMODE_TRACK_LIMIT_TRACKS;
break;
}
m_LimitCounter = 0;
m_LimitReached = false;
if( gaugeid != wxNOT_FOUND )
{
wxCommandEvent Event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
Event.SetInt( m_GaugeId );
Event.SetExtraLong( 100 );
wxPostEvent( guMainFrame::GetMainFrame(), Event );
}
m_LastFM = new guLastFM();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guSmartModeThread::~guSmartModeThread()
{
if( !TestDestroy() )
{
wxCommandEvent event( wxEVT_MENU, ID_SMARTMODE_THREAD_END );
wxPostEvent( m_Owner, event );
}
if( m_GaugeId != wxNOT_FOUND )
{
wxCommandEvent Event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
Event.SetInt( m_GaugeId );
wxPostEvent( guMainFrame::GetMainFrame(), Event );
}
if( m_LastFM )
delete m_LastFM;
}
// -------------------------------------------------------------------------------- //
void guSmartModeThread::SendTracks( guTrackArray * tracks )
{
if( !TestDestroy() )
{
wxCommandEvent event( wxEVT_MENU, ID_SMARTMODE_ADD_TRACKS );
event.SetClientData( ( void * ) tracks );
wxPostEvent( m_Owner, event );
}
else
{
if( tracks )
{
delete tracks;
}
}
}
// -------------------------------------------------------------------------------- //
bool guSmartModeThread::CheckLimit( const guTrack * track )
{
//guLogMessage( wxT( "%i ) CheckLimit %lli => %lli" ), m_LimitType, m_LimitCounter.GetValue(), m_TrackLimit.GetValue() );
if( track )
{
switch( m_LimitType )
{
case guSMARTMODE_TRACK_LIMIT_TRACKS :
if( m_LimitCounter >= m_TrackLimit )
{
return true;
}
m_LimitCounter++;
break;
case guSMARTMODE_TRACK_LIMIT_TIME_MINUTES :
case guSMARTMODE_TRACK_LIMIT_TIME_HOURS :
if( ( m_LimitCounter + track->m_Length ) >= m_TrackLimit )
{
m_LimitReached = true;
return true;
}
m_LimitCounter += track->m_Length;
break;
case guSMARTMODE_TRACK_LIMIT_SIZE_MB :
case guSMARTMODE_TRACK_LIMIT_SIZE_GB :
if( ( m_LimitCounter + track->m_FileSize ) >= m_TrackLimit )
{
m_LimitReached = true;
return true;
}
m_LimitCounter += track->m_FileSize;
break;
}
}
else
{
return m_LimitReached || ( m_LimitCounter >= m_TrackLimit );
}
if( m_GaugeId != wxNOT_FOUND )
{
wxCommandEvent Event( wxEVT_MENU, ID_STATUSBAR_GAUGE_UPDATE );
Event.SetInt( m_GaugeId );
Event.SetExtraLong( long( ( m_LimitCounter * 100 ) / m_TrackLimit ) );
wxPostEvent( guMainFrame::GetMainFrame(), Event );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guSmartModeThread::CheckAddTrack( const wxString &artistname, const wxString &trackname, guTrackArray * tracks )
{
//guLogMessage( wxT( "CheckAddTrack: '%s' - '%s'" ), artistname.c_str(), trackname.c_str() );
// Check if we added the artist before
if( !m_SmartAddedArtists || ( m_SmartAddedArtists->Index( artistname.Upper() ) == wxNOT_FOUND ) )
{
guTrack * Track = m_Db->FindSong( artistname, trackname, m_FilterAllowPlayList, m_FilterDenyPlayList );
if( Track )
{
//guLogMessage( wxT( "Similar: '%s' - '%s'" ), artistname.c_str(), trackname.c_str() );
// Check if we previously added the track
if( !m_SmartAddedTracks || ( m_SmartAddedTracks->Index( Track->m_SongId ) == wxNOT_FOUND ) )
{
//guLogMessage( wxT( "Found Track '%s' '%s'" ), LenToString( Track->m_Length ).c_str(), SizeToString( Track->m_FileSize ).c_str() );
Track->m_TrackMode = guTRACK_MODE_SMART;
tracks->Add( Track );
return true;
}
else
{
delete Track;
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
inline double MatchStr2Double( const wxString &match )
{
double Match;
wxString MatchStr = match;
MatchStr.Replace( wxT( "." ), wxLocale::GetInfo( wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER ) );
if( MatchStr.ToDouble( &Match ) )
{
return Match;
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guSmartModeThread::AddSimilarTracks( const wxString &artist, const wxString &track, guTrackArray * tracks )
{
//guLogMessage( wxT( "Searching for %s - %s" ), artist.c_str(), track.c_str() );
int AddedTracks = 0;
guTrackArray FoundTracks;
guSimilarTrackInfoArray SimilarTracks = m_LastFM->TrackGetSimilar( artist, track );
if( SimilarTracks.Count() )
{
int Count = SimilarTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
double Match = MatchStr2Double( SimilarTracks[ Index ].m_Match );
//guLogMessage( wxT( "Match: %f" ), Match );
if( Match >= guSMARTMODE_MIN_TRACK_MATCH )
{
CheckAddTrack( SimilarTracks[ Index ].m_ArtistName, SimilarTracks[ Index ].m_TrackName, &FoundTracks );
}
else // Results comes sorted by match
{
break;
}
// TODO: CHANGE LIMIT
if( TestDestroy() )
break;
}
}
if( FoundTracks.Count() < 4 )
{
guSimilarArtistInfoArray SimilarArtists = m_LastFM->ArtistGetSimilar( artist );
int Count = SimilarArtists.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( !m_SmartAddedArtists || ( m_SmartAddedArtists->Index( SimilarArtists[ Index ].m_Name.Upper() ) == wxNOT_FOUND ) )
{
double Match = MatchStr2Double( SimilarArtists[ Index ].m_Match );
if( Match >= guSMARTMODE_MIN_ARTIST_MATCH )
{
if( m_Db->GetArtistId( SimilarArtists[ Index ].m_Name, false ) != wxNOT_FOUND )
{
//guLogMessage( wxT( "Found similar artist: '%s'" ), SimilarArtists[ Index ].m_Name.c_str() );
guTopTrackInfoArray ArtistTopTracks = m_LastFM->ArtistGetTopTracks( SimilarArtists[ Index ].m_Name );
int TTIndex;
int TTCount = ArtistTopTracks.Count();
for( TTIndex = 0; TTIndex < TTCount; TTIndex++ )
{
if( TestDestroy() ||
CheckAddTrack( ArtistTopTracks[ TTIndex ].m_ArtistName, ArtistTopTracks[ TTIndex ].m_TrackName, &FoundTracks ) )
break;
}
}
}
else
{
break;
}
}
if( TestDestroy() )
break;
}
}
// Select some random tracks from the available
while( !TestDestroy() && FoundTracks.Count() )
{
int TrackIndex = guRandom( FoundTracks.Count() );
const guTrack & RandomTrack = FoundTracks[ TrackIndex ];
if( !m_SmartAddedArtists || ( m_SmartAddedArtists->Index( RandomTrack.m_ArtistName.Upper() ) == wxNOT_FOUND ) )
{
if( !m_SmartAddedTracks || ( m_SmartAddedTracks->Index( RandomTrack.m_SongId ) == wxNOT_FOUND ) )
{
if( !CheckLimit( &RandomTrack ) )
{
tracks->Add( new guTrack( RandomTrack ) );
if( m_SmartAddedArtists )
{
m_SmartAddedArtists->Add( RandomTrack.m_ArtistName.Upper() );
}
if( m_SmartAddedTracks )
{
m_SmartAddedTracks->Add( RandomTrack.m_SongId );
}
AddedTracks++;
}
else
{
break;
}
}
}
FoundTracks.RemoveAt( TrackIndex );
}
return AddedTracks;
}
// -------------------------------------------------------------------------------- //
guSmartModeThread::ExitCode guSmartModeThread::Entry()
{
if( m_LastFM )
{
guTrackArray * Tracks = new guTrackArray();
size_t TrackIndex = 0;
if( Tracks )
{
while( !TestDestroy() && !CheckLimit() )
{
AddSimilarTracks( m_ArtistName, m_TrackName, Tracks );
if( TrackIndex < Tracks->Count() )
{
const guTrack &AddedTrack = Tracks->Item( TrackIndex );
m_ArtistName = AddedTrack.m_ArtistName;
m_TrackName = AddedTrack.m_SongName;
TrackIndex++;
//guLogMessage( wxT( "SmartModeThread:: TrackIndex: %i" ), TrackIndex );
}
else
{
break;
}
}
// Remove the oldest added tracks or artists
if( m_SmartAddedTracks && ( ( int ) m_SmartAddedTracks->Count() > m_MaxSmartTracksList ) )
{
m_SmartAddedTracks->RemoveAt( 0, m_SmartAddedTracks->Count() - m_MaxSmartTracksList );
}
if( m_SmartAddedArtists && ( ( int ) m_SmartAddedArtists->Count() > m_MaxSmartArtistsList ) )
{
m_SmartAddedArtists->RemoveAt( 0, m_SmartAddedArtists->Count() - m_MaxSmartArtistsList );
}
//guLogDebug( wxT( "========" ) );
//for( int Index = 0; Index < m_SmartAddedArtists->Count(); Index++ )
// guLogDebug( wxT( "Artist: '%s'" ), ( * m_SmartAddedArtists )[ Index ].c_str() );
SendTracks( Tracks );
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guGenSmartPlaylist
// -------------------------------------------------------------------------------- //
guGenSmartPlaylist::guGenSmartPlaylist( wxWindow * parent, guMediaViewer * mediaviewer, const wxString &playlistname ) :
wxDialog( parent, wxID_ANY, _( "Generate Smart Playlist" ), wxDefaultPosition, wxSize( 500, 250 ), wxDEFAULT_DIALOG_STYLE )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_Playlists.Add( new guListItem( wxNOT_FOUND, _( "All" ) ) );
m_Db->GetPlayLists( &m_Playlists, guPLAYLIST_TYPE_STATIC );
m_Db->GetPlayLists( &m_Playlists, guPLAYLIST_TYPE_DYNAMIC );
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer * StaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxHORIZONTAL );
wxFlexGridSizer * FlexGridSizer = new wxFlexGridSizer( 2, 0, 0 );
FlexGridSizer->AddGrowableCol( 1 );
FlexGridSizer->SetFlexibleDirection( wxBOTH );
FlexGridSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticText * SaveToLabel = new wxStaticText( this, wxID_ANY, _( "Save to" ), wxDefaultPosition, wxDefaultSize, 0 );
SaveToLabel->Wrap( -1 );
FlexGridSizer->Add( SaveToLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
m_SaveToComboBox = new wxComboBox( this, wxID_ANY, playlistname, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
FlexGridSizer->Add( m_SaveToComboBox, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
int Count = m_Playlists.Count();
for( int Index = 1; Index < Count; Index++ )
{
m_SaveToComboBox->Append( m_Playlists[ Index ].m_Name );
}
wxStaticLine * StaticLineL = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
FlexGridSizer->Add( StaticLineL, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 );
wxStaticLine * StaticLineR = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
FlexGridSizer->Add( StaticLineR, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
wxStaticText * AllowLabel = new wxStaticText( this, wxID_ANY, _( "Allow" ), wxDefaultPosition, wxDefaultSize, 0 );
AllowLabel->Wrap( -1 );
FlexGridSizer->Add( AllowLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
wxArrayString FilterChoices;
Count = m_Playlists.Count();
for( int Index = 0; Index < Count; Index++ )
{
FilterChoices.Add( m_Playlists[ Index ].m_Name );
}
m_FilterAlowChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilterChoices, 0 );
m_FilterAlowChoice->SetSelection( 0 );
FlexGridSizer->Add( m_FilterAlowChoice, 1, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
wxStaticText * DenyLabel = new wxStaticText( this, wxID_ANY, _( "Deny" ), wxDefaultPosition, wxDefaultSize, 0 );
DenyLabel->Wrap( -1 );
FlexGridSizer->Add( DenyLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
FilterChoices[ 0 ] = _( "None" );
m_FilterDenyChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilterChoices, 0 );
m_FilterDenyChoice->SetSelection( 0 );
FlexGridSizer->Add( m_FilterDenyChoice, 0, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
wxStaticText * LimitLabel = new wxStaticText( this, wxID_ANY, _( "Limit to" ), wxDefaultPosition, wxDefaultSize, 0 );
LimitLabel->Wrap( -1 );
FlexGridSizer->Add( LimitLabel, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
wxBoxSizer* LimitSizer;
LimitSizer = new wxBoxSizer( wxHORIZONTAL );
m_LimitTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
LimitSizer->Add( m_LimitTextCtrl, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );
wxArrayString LimitChoices;
LimitChoices.Add( _( "Tracks" ) );
LimitChoices.Add( _( "Minutes" ) );
LimitChoices.Add( _( "Hours" ) );
LimitChoices.Add( _( "MiBytes" ) );
LimitChoices.Add( _("GiBytes" ) );
m_LimitChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, LimitChoices, 0 );
m_LimitChoice->SetSelection( 0 );
LimitSizer->Add( m_LimitChoice, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );
FlexGridSizer->Add( LimitSizer, 0, wxEXPAND, 5 );
StaticBoxSizer->Add( FlexGridSizer, 1, wxALIGN_CENTER_VERTICAL, 5 );
MainSizer->Add( StaticBoxSizer, 1, wxEXPAND|wxALL, 5 );
wxStdDialogButtonSizer * DlgButtons = new wxStdDialogButtonSizer();
wxButton * DlgButtonsOK = new wxButton( this, wxID_OK );
DlgButtons->AddButton( DlgButtonsOK );
wxButton * DlgButtonsCancel = new wxButton( this, wxID_CANCEL );
DlgButtons->AddButton( DlgButtonsCancel );
DlgButtons->Realize();
MainSizer->Add( DlgButtons, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
this->Fit();
}
// -------------------------------------------------------------------------------- //
guGenSmartPlaylist::~guGenSmartPlaylist()
{
}
// -------------------------------------------------------------------------------- //
int guGenSmartPlaylist::GetPlayListId( void )
{
int Selection = m_SaveToComboBox->GetSelection();
if( Selection == wxNOT_FOUND && m_SaveToComboBox->GetCount() != 0 )
{
Selection = FindPlayListItem( &m_Playlists, m_SaveToComboBox->GetValue().Lower().Trim().Trim( false ) );
}
return Selection;
}
}
// -------------------------------------------------------------------------------- //
| 18,999
|
C++
|
.cpp
| 441
| 34.612245
| 148
| 0.565022
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,569
|
AcousticId.cpp
|
anonbeat_guayadeque/src/info/musicbrainz/AcousticId.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AcousticId.h"
#include "EventCommandIds.h"
#include "MusicBrainz.h"
#include "Utils.h"
#include "Version.h"
#include <wx/sstream.h>
#include <wx/uri.h>
namespace Guayadeque {
#define guACOUSTICID_URL wxT( "http://api.acoustid.org/v2/lookup?client=0ND2BN8mP3&duration=%i&format=xml&meta=recordings+compress&fingerprint=%s" )
#define guACOUSTICID_CLIENT_ID "0ND2BN8mP3"
// -------------------------------------------------------------------------------- //
// guAcousticIdThread
// -------------------------------------------------------------------------------- //
class guAcousticIdThread : public wxThread
{
protected :
wxString m_FileName;
bool m_Running;
guAcousticId * m_AcousticId;
GstElement * m_Pipeline;
unsigned int m_Start;
unsigned int m_Length;
bool BuildPipeline( void );
public :
guAcousticIdThread( guAcousticId * acousticid, const wxChar * filename,
const unsigned int start = 0, const unsigned int length = wxNOT_FOUND );
~guAcousticIdThread();
virtual ExitCode Entry();
void SetFingerprint( const char * fingerprint );
void Stop( void );
};
// -------------------------------------------------------------------------------- //
extern "C" {
#define GST_TAG_CHROMAPRINT_FINGERPRINT "chromaprint-fingerprint"
// -------------------------------------------------------------------------------- //
static gboolean gst_bus_async_callback( GstBus * bus, GstMessage * message, guAcousticIdThread * pobj )
{
//guLogMessage( wxT( "Got gstreamer message %u" ), GST_MESSAGE_TYPE( message ) );
switch( GST_MESSAGE_TYPE( message ) )
{
case GST_MESSAGE_ERROR :
{
GError * err;
gchar * debug;
gst_message_parse_error( message, &err, &debug );
guLogError( wxT( "Gstreamer error '%s'" ), wxString( err->message, wxConvUTF8 ).c_str() );
g_error_free( err );
g_free( debug );
pobj->Stop();
break;
}
case GST_MESSAGE_EOS :
{
//guLogMessage( wxT( "EOS Detected..." ) );
pobj->Stop();
break;
}
case GST_MESSAGE_TAG :
{
/* The stream discovered new tags. */
GstTagList * tags;
gchar * fingerprint = NULL;
/* Extract from the message the GstTagList.
* This generates a copy, so we must remember to free it.*/
gst_message_parse_tag( message, &tags );
gst_tag_list_get_string( tags, GST_TAG_CHROMAPRINT_FINGERPRINT, &fingerprint );
if( fingerprint )
{
//guLogMessage( wxT( "Gstreamer got fingerprint '%s'" ), wxString( fingerprint, wxConvUTF8 ).c_str() );
pobj->SetFingerprint( fingerprint );
g_free( fingerprint );
}
/* Free the tag list */
gst_tag_list_unref( tags );
break;
}
default:
break;
}
return TRUE;
}
// -------------------------------------------------------------------------------- //
static void on_pad_added( GstElement * comp, GstPad * pad, GstElement * conv )
{
GstCaps * caps;
GstStructure * str;
GstPad * convpad;
//guLogMessage( wxT( "New pad created..." ) );
convpad = gst_element_get_static_pad( conv, "sink" );
if( GST_PAD_IS_LINKED( convpad ) )
{
g_object_unref( convpad );
return;
}
/* check media type */
caps = gst_pad_query_caps( pad, NULL );
str = gst_caps_get_structure( caps, 0 );
if( !g_strrstr( gst_structure_get_name( str ), "audio" ) )
{
gst_caps_unref( caps );
gst_object_unref( convpad );
return;
}
gst_caps_unref( caps );
//guLogMessage( wxT( "Linked composer and converter..." ) );
/* link'n'play */
gst_pad_link( pad, convpad );
g_object_unref( convpad );
}
}
// -------------------------------------------------------------------------------- //
// guAcousticIdThread
// -------------------------------------------------------------------------------- //
guAcousticIdThread::guAcousticIdThread( guAcousticId * AcousticId, const wxChar * filename,
const unsigned int start, const unsigned int length )
{
//guLogMessage( wxT( "guAcousticIdThread..." ) );
m_AcousticId = AcousticId;
m_FileName = wxString( filename );
m_Running = false;
int Error = guAcousticId::guAID_STATUS_ERROR_GSTREAMER;
m_Start = start;
m_Length = length;
if( BuildPipeline() )
{
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
else
{
Error = guAcousticId::guAID_STATUS_ERROR_THREAD;
m_AcousticId->SetStatus( Error );
}
}
}
// -------------------------------------------------------------------------------- //
guAcousticIdThread::~guAcousticIdThread()
{
if( GST_IS_ELEMENT( m_Pipeline ) )
{
gst_element_set_state( m_Pipeline, GST_STATE_NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_remove_watch( bus );
gst_object_unref( G_OBJECT( bus ) );
gst_object_unref( GST_OBJECT( m_Pipeline ) );
m_Pipeline = NULL;
}
m_AcousticId->ClearAcousticIdThread();
//guLogMessage( wxT( "Destroyed AcousticIdThread..." ) );
}
// -------------------------------------------------------------------------------- //
bool guAcousticIdThread::BuildPipeline( void )
{
m_Pipeline = gst_pipeline_new( "guPipeline" );
if( GST_IS_ELEMENT( m_Pipeline ) )
{
GstElement * src;
src = gst_element_factory_make( "giosrc", "guTransSource" );
if( GST_IS_ELEMENT( src ) )
{
wxString Location;
wxURI URI( m_FileName );
if( URI.IsReference() )
{
Location = wxT( "file://" ) + m_FileName;
}
else
{
if( !URI.HasScheme() )
{
Location = wxT( "http://" ) + m_FileName;
}
else
{
Location = m_FileName;
}
}
g_object_set( G_OBJECT( src ), "location", ( const char * ) Location.mb_str( wxConvFile ), NULL );
GstElement * dec;
dec = gst_element_factory_make( "decodebin", "guTransDecoder" );
if( GST_IS_ELEMENT( dec ) )
{
GstElement * conv = gst_element_factory_make( "audioconvert", "guConverter" );
if( GST_IS_ELEMENT( conv ) )
{
GstElement * chrom = gst_element_factory_make( "chromaprint", "guChroma" );
if( GST_IS_ELEMENT( chrom ) )
{
g_object_set( G_OBJECT( chrom ), "duration", 60, NULL );
GstElement * fake = gst_element_factory_make( "fakesink", "guFakeSink" );
if( GST_IS_ELEMENT( fake ) )
{
g_object_set( G_OBJECT( fake ), "sync", 0, NULL );
gst_bin_add_many( GST_BIN( m_Pipeline ), src, dec, conv, chrom, fake, NULL );
g_object_set( m_Pipeline, "async-handling", true, NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_add_watch( bus, ( GstBusFunc ) gst_bus_async_callback, this );
gst_object_unref( G_OBJECT( bus ) );
if( gst_element_link( src, dec ) )
{
g_signal_connect( dec, "pad-added", G_CALLBACK( on_pad_added ), conv );
if( gst_element_link_many( conv, chrom, fake, NULL ) )
{
gst_element_set_state( m_Pipeline, GST_STATE_PAUSED );
//guLogMessage( wxT( "Created the pipeline..." ) );
return true;
}
else
{
guLogError( wxT( "Error linking the objects src, dec, conv, chrom, fake" ) );
}
}
else
{
guLogError( wxT( "couldnt link the source and the decoder" ) );
}
gst_object_unref( fake );
}
else
{
guLogError( wxT( "Error creating the AcousticId sink" ) );
}
gst_object_unref( chrom );
}
else
{
guLogError( wxT( "Error creating the AcousticId chromaprint" ) );
}
gst_object_unref( conv );
}
else
{
guLogError( wxT( "Error creating the AcousticId converter" ) );
}
gst_object_unref( dec );
}
else
{
guLogError( wxT( "Error creating the AcousticId decoder" ) );
}
gst_object_unref( src );
}
else
{
guLogError( wxT( "Error creating the AcousticId source" ) );
}
gst_object_unref( m_Pipeline );
}
else
{
guLogError( wxT( "Error creating the AcousticId pipeline" ) );
}
return false;
}
// -------------------------------------------------------------------------------- //
guAcousticIdThread::ExitCode guAcousticIdThread::Entry()
{
gst_element_set_state( m_Pipeline, GST_STATE_PLAYING );
m_Running = true;
while( !TestDestroy() && m_Running )
{
Sleep( 2000 );
//gint64 Pos = -1;
//gst_element_query_position( m_Pipeline, GST_FORMAT_TIME, &Pos );
//guLogMessage( wxT( "Running...%llu" ), Pos );
}
//guLogMessage( wxT( "Finished guAcousticIdThread..." ) );
return 0;
}
// -------------------------------------------------------------------------------- //
void guAcousticIdThread::SetFingerprint( const char * fingerprint )
{
m_AcousticId->SetFingerprint( fingerprint );
Stop();
}
// -------------------------------------------------------------------------------- //
void guAcousticIdThread::Stop( void )
{
//gst_element_set_state( m_Pipeline, GST_STATE_PAUSED );
m_Running = false;
}
// -------------------------------------------------------------------------------- //
// guAcousticId
// -------------------------------------------------------------------------------- //
guAcousticId::guAcousticId( guAcousticIdClient * acousticidclient )
{
m_AcousticIdThread = NULL;
m_AcousticIdClient = acousticidclient;
m_Status = guAID_STATUS_OK;
}
// -------------------------------------------------------------------------------- //
guAcousticId::~guAcousticId()
{
if( m_AcousticIdThread )
{
m_AcousticIdThread->Pause();
m_AcousticIdThread->Delete();
}
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SearchTrack( const guTrack * track )
{
m_Track = track;
m_MBId.Clear();
m_Fingerprint.Clear();
DoGetFingerprint();
}
// -------------------------------------------------------------------------------- //
wxString guAcousticId::GetXmlDoc( void )
{
return m_XmlDoc;
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SetFingerprint( const wxString &fingerprint )
{
m_Fingerprint = fingerprint;
m_AcousticIdClient->OnAcousticIdFingerprintFound( m_Fingerprint );
if( !m_Fingerprint.IsEmpty() )
{
DoGetMetadata();
}
else
{
SetStatus( guAID_STATUS_ERROR_NO_FINGERPRINT );
}
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SetFingerprint( const char * fingerprint )
{
SetFingerprint( wxString( fingerprint, wxConvUTF8 ) );
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SetXmlDoc( const wxString &xmldoc )
{
}
// -------------------------------------------------------------------------------- //
wxString guAcousticId::GetMBId( void )
{
return m_MBId;
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SetMBId( const wxString &mbid )
{
m_MBId = mbid;
if( m_AcousticIdThread )
{
CancelSearch();
}
//guLogMessage( wxT( "Calling OnFingerprintFound..." ) );
m_AcousticIdClient->OnAcousticIdMBIdFound( m_MBId );
}
// -------------------------------------------------------------------------------- //
void guAcousticId::ClearAcousticIdThread( void )
{
m_AcousticIdThread = NULL;
}
// -------------------------------------------------------------------------------- //
bool guAcousticId::IsRunning( void )
{
return m_AcousticIdThread != NULL;
}
// -------------------------------------------------------------------------------- //
void guAcousticId::CancelSearch( void )
{
if( m_AcousticIdThread )
{
m_AcousticIdThread->Pause();
m_AcousticIdThread->Delete();
m_AcousticIdThread = NULL;
}
}
// -------------------------------------------------------------------------------- //
bool guAcousticId::DoGetFingerprint( void )
{
//guLogMessage( wxT( "DoGetFingerprint..." ) );
if( m_Track )
{
if( m_AcousticIdThread )
{
CancelSearch();
}
m_AcousticIdThread = new guAcousticIdThread( this, m_Track->m_FileName.c_str() );
}
return m_AcousticIdThread != NULL;
}
// -------------------------------------------------------------------------------- //
bool guAcousticId::DoGetMetadata( void )
{
wxString ReqUrl = wxString::Format( guACOUSTICID_URL,
m_Track->m_Length / 1000,
m_Fingerprint.c_str() );
//guLogMessage( ReqUrl );
wxString Content = GetUrlContent( ReqUrl );
if( !Content.IsEmpty() )
{
m_XmlDoc = Content;
return DoParseXmlDoc();
}
else
{
SetStatus( guAID_STATUS_ERROR_HTTP );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guAcousticId::DoParseXmlDoc( void )
{
/*
<response>
<status>ok</status>
<results>
<result>
<recordings>
<recording>
<duration>138</duration>
<title>Don't Panic</title>
<id>0f87975c-5e6a-4a42-a19a-fed67f0d3560</id>
<artists>
<artist>
<id>cc197bad-dc9c-440d-a5b5-d52ba2e14234</id>
<name>Coldplay</name>
</artist>
</artists>
</recording>
<recording>...</recording>
<recording>...</recording>
</recordings>
<score>0.994859</score>
<id>0fc6a463-6845-4181-a354-66e326c6db57</id>
</result>
<result>...</result>
<result>...</result>
</results>
</response>
*/
//guLogMessage( wxT( "XML Response: %s" ), m_XmlDoc.c_str() );
wxStringInputStream ins( m_XmlDoc );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && ( XmlNode->GetName() == wxT( "response" ) ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
//guLogMessage( wxT( "AcousticId xml %s => %s" ), XmlNode->GetName().c_str(), XmlNode->GetNodeContent().c_str() );
if( XmlNode->GetName() == wxT( "status" ) )
{
if( XmlNode->GetNodeContent() != wxT( "ok" ) )
{
SetStatus( guAID_STATUS_ERROR_BAD_STATUS );
return false;
}
}
else if( XmlNode->GetName() == wxT( "results" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "result" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "recordings" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "recording" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "id" ) )
{
SetMBId( XmlNode->GetNodeContent() );
return true;
}
XmlNode = XmlNode->GetNext();
}
SetStatus( guAID_STATUS_ERROR_XMLPARSE );
}
else
{
SetStatus( guAID_STATUS_ERROR_XMLERROR );
}
return false;
}
// -------------------------------------------------------------------------------- //
void guAcousticId::SetStatus( const int status )
{
m_Status = status;
m_AcousticIdClient->OnAcousticIdError( m_Status );
}
// -------------------------------------------------------------------------------- //
int guAcousticId::GetStatus( void )
{
return m_Status;
}
// -------------------------------------------------------------------------------- //
bool guAcousticId::IsOk( void )
{
return m_Status == guAID_STATUS_OK;
}
}
// -------------------------------------------------------------------------------- //
| 18,372
|
C++
|
.cpp
| 529
| 27.659735
| 153
| 0.477815
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,570
|
MusicBrainz.cpp
|
anonbeat_guayadeque/src/info/musicbrainz/MusicBrainz.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "MusicBrainz.h"
//#include "Http.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/sstream.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guMBRecordingArray )
WX_DEFINE_OBJARRAY( guMBReleaseArray )
// -------------------------------------------------------------------------------- //
#define guMB_URL_BASE "http://musicbrainz.org/ws/2/"
#define guMB_URL_RELEASES_BY_TEXT guMB_URL_BASE "release/?query=artist:%s,title:%s"
#define guMB_URL_RELEASES_BY_RECORDING_ID guMB_URL_BASE "recording/%s?inc=releases"
#define guMB_URL_RECORDINGS_BY_RELEASE_ID guMB_URL_BASE "release/%s?inc=recordings%%20artists%%20artist-credits"
#define guMB_URL_RECORDING_BY_ID guMB_URL_BASE "recording/%s?inc=artists%%20artist-credits"
#define guMB_URL_RELEASES_BY_DISCID guMB_URL_BASE "discid/%s"
// -------------------------------------------------------------------------------- //
guMusicBrainz::guMusicBrainz()
{
}
// -------------------------------------------------------------------------------- //
guMusicBrainz::~guMusicBrainz()
{
}
// -------------------------------------------------------------------------------- //
static void ReadXmlReleaseArtist( wxXmlNode * XmlNode, guMBRelease * mbrelease )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name-credit" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode->GetAttribute( wxT( "id" ), &mbrelease->m_ArtistId );
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "name" ) )
{
mbrelease->m_ArtistName = XmlNode->GetNodeContent();
return;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
static void ReadXmlReleaseArtist( wxXmlNode * XmlNode, guMBRecording * mbrecording )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name-credit" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode->GetAttribute( wxT( "id" ), &mbrecording->m_ArtistId );
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "name" ) )
{
mbrecording->m_ArtistName = XmlNode->GetNodeContent();
return;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
static void ReadXmlRelease( wxXmlNode * XmlNode, guMBRelease * mbrelease )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "title" ) )
{
mbrelease->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "artist-credit" ) )
{
ReadXmlReleaseArtist( XmlNode->GetChildren(), mbrelease );
}
else if( XmlNode->GetName() == wxT( "date" ) )
{
long Year = 0;
if( XmlNode->GetNodeContent().Left( 4 ).ToLong( &Year ) )
{
mbrelease->m_Year = Year;
}
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
static void ReadXmlReleases( wxXmlNode * XmlNode, guMBReleaseArray * mbreleases )
{
while( XmlNode && XmlNode->GetName() == wxT( "release" ) )
{
wxString ReleaseId;
XmlNode->GetAttribute( wxT( "id" ), &ReleaseId );
if( FindMBReleaseId( mbreleases, ReleaseId ) == wxNOT_FOUND )
{
guMBRelease * MBRelease = new guMBRelease();
MBRelease->m_Id = ReleaseId;
ReadXmlRelease( XmlNode->GetChildren(), MBRelease );
mbreleases->Add( MBRelease );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlReleaseRecording( wxXmlNode * xmlnode, guMBRecording * mbrecording )
{
while( xmlnode )
{
if( xmlnode->GetName() == wxT( "title" ) )
{
mbrecording->m_Title = xmlnode->GetNodeContent();
}
else if( xmlnode->GetName() == wxT( "length" ) )
{
long Len = 0;
if( xmlnode->GetNodeContent().ToLong( &Len ) )
{
mbrecording->m_Length = Len;
}
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlReleaseTrackList( wxXmlNode * xmlnode, guMBRelease * mbrelease )
{
while( xmlnode )
{
if( xmlnode->GetName() == "track" )
{
guMBRecording * MBRecording = new guMBRecording();
ReadXmlReleaseRecording( xmlnode->GetChildren(), MBRecording );
mbrelease->m_Recordings.Add( MBRecording );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadXmlCdStub( wxXmlNode * xmlnode, guMBRelease * mbrelease )
{
while( xmlnode )
{
if( xmlnode->GetName() == wxT( "title" ) )
{
mbrelease->m_Title = xmlnode->GetNodeContent();
}
else if( xmlnode->GetName() == wxT( "artist" ) )
{
mbrelease->m_ArtistName = xmlnode->GetNodeContent();
}
else if( xmlnode->GetName() == wxT( "track-list" ) )
{
ReadXmlReleaseTrackList( xmlnode->GetChildren(), mbrelease );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
int guMusicBrainz::GetRecordReleases( const wxString &artist, const wxString &title, guMBReleaseArray * mbreleases )
{
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RELEASES_BY_TEXT ),
guURLEncode( artist ).c_str(),
guURLEncode( title ).c_str() );
//guLogMessage( wxT( "GetRelease: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "error" ) )
{
m_ErrorMsg = XmlNode->GetNodeContent();
return -1;
}
else if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode && XmlNode->GetName() == wxT( "release-list" ) )
{
ReadXmlReleases( XmlNode->GetChildren(), mbreleases );
}
XmlNode = XmlNode->GetNext();
}
}
return mbreleases->Count();
}
// -------------------------------------------------------------------------------- //
int guMusicBrainz::GetRecordReleases( const wxString &recordid, guMBReleaseArray * mbreleases )
{
if( recordid.IsEmpty() )
{
guLogError( wxT( "The MusicBrainz recordid is empty" ) );
return wxNOT_FOUND;
}
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RELEASES_BY_RECORDING_ID ),
recordid.c_str() );
//guLogMessage( wxT( "MusicBrainz: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
//guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "error" ) )
{
m_ErrorMsg = XmlNode->GetNodeContent();
return -1;
}
else if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "recording" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "release-list" ) )
{
ReadXmlReleases( XmlNode->GetChildren(), mbreleases );
}
XmlNode = XmlNode->GetNext();
}
}
return mbreleases->Count();
}
// -------------------------------------------------------------------------------- //
int guMusicBrainz::GetDiscIdReleases( const wxString &discid, guMBReleaseArray * mbreleases )
{
if( discid.IsEmpty() )
{
guLogError( wxT( "The MusicBrainz discid is empty" ) );
return wxNOT_FOUND;
}
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RELEASES_BY_DISCID ),
discid.c_str() );
//guLogMessage( wxT( "MusicBrainz: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
//guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "error" ) )
{
m_ErrorMsg = XmlNode->GetNodeContent();
return -1;
}
else if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "disc" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "cdstub" ) )
{
guMBRelease * MBRelease = new guMBRelease();
XmlNode->GetAttribute( wxT( "id" ), &MBRelease->m_Id );
ReadXmlCdStub( XmlNode->GetChildren(), MBRelease );
mbreleases->Add( MBRelease );
}
else if( XmlNode->GetName() == wxT( "release-list" ) )
{
ReadXmlReleases( XmlNode->GetChildren(), mbreleases );
}
XmlNode = XmlNode->GetNext();
}
}
return mbreleases->Count();
}
// -------------------------------------------------------------------------------- //
static void ReadXmlRecording( wxXmlNode * XmlNode, guMBRecording * mbrecording )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "position" ) )
{
long Pos = 0;
if( XmlNode->GetNodeContent().ToLong( &Pos ) )
{
mbrecording->m_Number = Pos;
}
}
else if( XmlNode->GetName() == wxT( "title" ) && mbrecording->m_Title.IsEmpty() )
{
mbrecording->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "length" ) && !mbrecording->m_Length )
{
long Length = 0;
if( XmlNode->GetNodeContent().ToLong( &Length ) )
{
mbrecording->m_Length = Length;
}
}
else if( XmlNode->GetName() == wxT( "recording" ) )
{
XmlNode->GetAttribute( wxT( "id" ), &mbrecording->m_Id );
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "artist-credit" ) )
{
ReadXmlReleaseArtist( XmlNode->GetChildren(), mbrecording );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
static void ReadXmlRecordings( wxXmlNode * XmlNode, guMBRecordingArray * mbrecordings )
{
while( XmlNode && XmlNode->GetName() == wxT( "track" ) )
{
guMBRecording * mbrecording = new guMBRecording();
ReadXmlRecording( XmlNode->GetChildren(), mbrecording );
mbrecordings->Add( mbrecording );
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
int guMusicBrainz::GetRecordings( const wxString &releaseid, guMBRecordingArray * mbrecordings )
{
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RECORDINGS_BY_RELEASE_ID ),
releaseid.c_str() );
//guLogMessage( wxT( "MusicBrainz: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
//guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "release" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "medium-list" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "medium" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "track-list" ) )
{
ReadXmlRecordings( XmlNode->GetChildren(), mbrecordings );
}
XmlNode = XmlNode->GetNext();
}
}
return mbrecordings->Count();
}
// -------------------------------------------------------------------------------- //
static void ReadXmlNodeArtist( wxXmlNode * XmlNode, guMBRelease &mbrelase )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name-credit" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode->GetAttribute( wxT( "Id" ), mbrelase.m_ArtistId );
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "name" ) )
{
mbrelase.m_ArtistName = XmlNode->GetNodeContent();
break;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
int guMusicBrainz::GetRecordings( guMBRelease &mbrelease )
{
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RECORDINGS_BY_RELEASE_ID ),
mbrelease.m_Id.c_str() );
//guLogMessage( wxT( "MusicBrainz: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "release" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "title" ) )
{
mbrelease.m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "artist-credit" ) )
{
ReadXmlNodeArtist( XmlNode->GetChildren(), mbrelease );
}
else if( XmlNode->GetName() == wxT( "date" ) )
{
long Year = 0;
if( XmlNode->GetNodeContent().Left( 4 ).ToLong( &Year ) )
{
mbrelease.m_Year = Year;
}
}
else if( XmlNode->GetName() == wxT( "medium-list" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "medium" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "track-list" ) )
{
ReadXmlRecordings( XmlNode->GetChildren(), &mbrelease.m_Recordings );
}
XmlNode = XmlNode->GetNext();
}
}
return mbrelease.m_Recordings.Count();
}
// -------------------------------------------------------------------------------- //
static void ReadXmlNodeArtist( wxXmlNode * XmlNode, guMBRecording * mbrecording )
{
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "name-credit" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode->GetAttribute( wxT( "Id" ), mbrecording->m_ArtistId );
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "name" ) )
{
mbrecording->m_ArtistName = XmlNode->GetNodeContent();
break;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void guMusicBrainz::GetRecordingInfo( const wxString &recordingid, guMBRecording * mbrecording )
{
wxString QueryUrl = wxString::Format( wxT( guMB_URL_RECORDING_BY_ID ),
recordingid.c_str() );
//guLogMessage( wxT( "MusicBrainz: %s" ), QueryUrl.c_str() );
wxString Content = GetUrlContent( QueryUrl );
//guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
if( Content.Length() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "metadata" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "recording" ) )
{
XmlNode = XmlNode->GetChildren();
continue;
}
else if( XmlNode->GetName() == wxT( "title" ) )
{
mbrecording->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "length" ) )
{
long Length = 0;
if( XmlNode->GetNodeContent().ToLong( &Length ) )
{
mbrecording->m_Length = Length;
}
}
else if( XmlNode->GetName() == wxT( "artist-credit" ) )
{
ReadXmlNodeArtist( XmlNode->GetChildren(), mbrecording );
}
XmlNode = XmlNode->GetNext();
}
}
}
// -------------------------------------------------------------------------------- //
// Others
// -------------------------------------------------------------------------------- //
int FindMBReleaseId( guMBReleaseArray * mbreleases, const wxString &releaseid )
{
int Count = mbreleases->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( mbreleases->Item( Index ).m_Id == releaseid )
return Index;
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 21,109
|
C++
|
.cpp
| 576
| 27.423611
| 116
| 0.475725
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,571
|
AudioScrobble.cpp
|
anonbeat_guayadeque/src/info/audioscrobble/AudioScrobble.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AudioScrobble.h"
#include "Config.h"
#include "MainFrame.h"
#include "MD5.h"
#include "PlayerPanel.h"
#include "Utils.h"
#include <wx/tokenzr.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guAudioScrobbleSender::guAudioScrobbleSender( guDbLibrary * db, const wxString &serverurl )
{
m_Db = db;
m_ServerUrl = serverurl;
ReadUserConfig();
m_SessionId = wxEmptyString;
m_NowPlayUrl = wxEmptyString;
m_SubmitUrl = wxEmptyString;
m_ErrorCode = guAS_ERROR_NOSESSION;
}
// -------------------------------------------------------------------------------- //
guAudioScrobbleSender::~guAudioScrobbleSender()
{
}
// -------------------------------------------------------------------------------- //
void guAudioScrobbleSender::OnConfigUpdated( void )
{
ReadUserConfig();
}
// -------------------------------------------------------------------------------- //
int guAudioScrobbleSender::ProcessError( const wxString &ErrorStr )
{
//guLogMessage( wxT( "ProcessError: '%s'" ), ErrorStr.c_str() );
if( ErrorStr.Contains( wxT( "BANNED" ) ) )
{
m_ErrorCode = guAS_ERROR_BANNED;
guLogError( wxT( "This Client version have been banned. You should upgrade to the newest version" ) );
m_SessionId = wxEmptyString;
}
else if( ErrorStr.Contains( wxT( "BADAUTH" ) ) )
{
m_ErrorCode = guAS_ERROR_BADAUTH;
guLogError( wxT( "The username or password is incorrect" ) );
m_SessionId = wxEmptyString;
}
else if( ErrorStr.Contains( wxT( "BADTIME" ) ) )
{
m_ErrorCode = guAS_ERROR_BADTIME;
guLogError( wxT( "The system clock is incorrect. Please adjuts time/date and try again." ) );
}
else if( ErrorStr.Contains( wxT( "FAILED" ) ) )
{
m_ErrorCode = guAS_ERROR_FAILED;
guLogError( wxT( "Server Error when connecting to LastFM server : " ) + ErrorStr );
}
else
{
m_ErrorCode = guAS_ERROR_UNKNOWN;
m_SessionId = wxEmptyString;
guLogError( wxT( "Unknown Error autenticating to LastFM server " ) + ErrorStr );
}
return m_ErrorCode;
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobbleSender::GetSessionId( void )
{
//guLogMessage( wxT( "guAudioScrobbleSender:GetSessionId" ) );
//http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=<client-id>&v=<client-ver>&u=<user>&t=<timestamp>&a=<auth>
wxString Content;
long LocalTime = wxGetUTCTime();
wxString AS_Url = m_ServerUrl + wxT( "?hs=true" )\
wxT( "&p=" ) guAS_PROTOCOL_VERSION\
wxT( "&c=" ) guAS_CLIENT_ID\
wxT( "&v=" ) guAS_CLIENT_VERSION\
wxT( "&u=" ) + m_UserName +
wxT( "&t=" ) + wxString::Format( wxT( "%lu" ), LocalTime ) +
wxT( "&a=" ) + GetAuthToken( LocalTime );
//guLogMessage( wxT( "AudioScrobble:GetSesionId : " ) + AS_Url );
char * Buffer = NULL;
guHttp Http;
Http.AddHeader( wxT( "User-Agent" ), guDEFAULT_BROWSER_USER_AGENT );
Http.AddHeader( wxT( "Accept" ), wxT( "text/html" ) );
Http.AddHeader( wxT( "Accept-Charset" ), wxT( "utf-8" ) );
Http.Get( Buffer, AS_Url );
if( Buffer )
{
Content = wxString( Buffer, wxConvUTF8 );
free( Buffer );
if( !Content.IsEmpty() )
{
//guLogMessage( wxT( "AudioScrobble:Response : " ) + Content );
wxArrayString Response = wxStringTokenize( Content );
if( Response.Count() && !Response[ 0 ].IsEmpty() )
{
if( Response[ 0 ] == wxT( "OK" ) && Response.Count() == 4 )
{
// All went Ok
m_SessionId = Response[ 1 ];
m_NowPlayUrl = Response[ 2 ];
m_SubmitUrl = Response[ 3 ];
//guLogMessage( wxT( "SessionId : " ) + SessionId );
//guLogMessage( wxT( "NowPlayUrl : " ) + NowPlayUrl );
//guLogMessage( wxT( "SubmitUrl : " ) + SubmitUrl );
m_ErrorCode = guAS_ERROR_NOERROR;
guLogMessage( wxT( "Loged in to : " ) + m_ServerUrl );
//return !SessionId.IsEmpty() && !SubmitUrl.IsEmpty() && !NowPlayUrl.IsEmpty();
}
else
{
ProcessError( Content );
guLogError( wxT( "Could not get the SessionId from: " ) + m_ServerUrl );
}
}
}
}
return m_ErrorCode == guAS_ERROR_NOERROR;
}
// -------------------------------------------------------------------------------- //
wxString guAudioScrobbleSender::GetAuthToken( int TimeStamp )
{
guMD5 md5;
return md5.MD5( m_Password + wxString::Format( wxT( "%u" ), TimeStamp ) );
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobbleSender::SubmitPlayedSongs( const guAS_SubmitInfoArray &PlayedSongs )
{
//guLogMessage( wxT( "guAudioScrobbleSender::SubmitPlayedSongs" ) );
wxString PostData;
wxString Content;
wxString Artist;
wxString Album;
wxString Track;
guHttp Http;
/*
s=<sessionID>
The Session ID string returned by the handshake request. Required.
a[0]=<artist>
The artist name. Required.
t[0]=<track>
The track title. Required.
i[0]=<time>
The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, January 1st 1970 UTC). This must be in the UTC time zone, and is required.
o[0]=<source>
The source of the track. Required, must be one of the following codes:
P
Chosen by the user (the most common value, unless you have a reason for choosing otherwise, use this).
R
Non-personalised broadcast (e.g. Shoutcast, BBC Radio 1).
E
Personalised recommendation except Last.fm (e.g. Pandora, Launchcast).
L
Last.fm (any mode). In this case, the 5-digit Last.fm recommendation key must be appended to this source ID to prove the validity of the submission (for example, "o[0]=L1b48a").
r[0]=<rating>
A single character denoting the rating of the track. Empty if not applicable.
L
Love (on any mode if the user has manually loved the track). This implies a listen.
B
Ban (only if source=L). This implies a skip, and the client should skip to the next track when a ban happens.
S
Skip (only if source=L)
Note: Currently a Last.fm web service must also be called to set love (track.love) or ban (track.ban) status. We anticipate that the next version of the scrobble protocol will no longer perform love and ban and this will instead be handled by the web services only.
l[0]=<secs>
The length of the track in seconds. Required when the source is P, optional otherwise.
b[0]=<album>
The album title, or an empty string if not known.
n[0]=<tracknumber>
The position of the track on the album, or an empty string if not known.
m[0]=<mb-trackid>
The MusicBrainz Track ID, or an empty string if not known.
*/
int count = PlayedSongs.Count();
if( count )
{
if( m_SessionId.IsEmpty() && !GetSessionId() )
return false;
PostData = wxT( "s=" ) + m_SessionId + wxT( "&" );
for( int index = 0; index < count; index++ )
{
Artist = guURLEncode( PlayedSongs[ index ].m_ArtistName );
Track = guURLEncode( PlayedSongs[ index ].m_TrackName );
Album = guURLEncode( PlayedSongs[ index ].m_AlbumName );
//
PostData += wxString::Format( wxT( "a[%u]=%s&t[%u]=%s&i[%u]=%u&o[%u]=%c&r[%u]=%c&l[%u]=%s&b[%u]=%s&n[%u]=%s&m[%u]=&" ),
index, Artist.c_str(),
index, Track.c_str(),
index, PlayedSongs[ index ].m_PlayedTime,
index, PlayedSongs[ index ].m_Source,
index, PlayedSongs[ index ].m_Rating,
index, ( PlayedSongs[ index ].m_TrackLen ) ?
wxString::Format( wxT( "%u" ), PlayedSongs[ index ].m_TrackLen ).c_str() :
wxEmptyString,
index, Album.c_str(),
index, ( PlayedSongs[ index ].m_TrackNum > 0 ) ?
wxString::Format( wxT( "%u" ), PlayedSongs[ index ].m_TrackNum ).c_str() :
wxEmptyString,
index );
}
PostData.RemoveLast( 1 ); // we remove the last & added
//guLogMessage( wxT( "AudioScrobble::Played : %s" ), PostData.c_str() );
Http.AddHeader( wxT( "Content-Type" ), wxT( "application/x-www-form-urlencoded" ) );
if( Http.Post( PostData.ToAscii(), PostData.Length(), m_SubmitUrl ) )
{
Content = Http.GetResData();
if( !Content.IsEmpty() )
{
//guLogMessage( wxT( "AudioScrobble::Response :\n%s" ), Content.c_str() );
if( Content.Contains( wxT( "OK" ) ) )
{
m_ErrorCode = guAS_ERROR_NOERROR;
return true;
}
else
{
guLogMessage( wxT( "AudioScrobble::PlayedTracks: \n%s\n%s" ), m_SubmitUrl.c_str(), PostData.c_str() );
guLogMessage( wxT( "AudioScrobble::Response : " ) + Content );
ProcessError( Content );
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobbleSender::SubmitNowPlaying( const guAS_SubmitInfo * cursong )
{
guHttp Http;
wxString PostData;
wxString Content;
wxString Artist;
wxString Album;
wxString Track;
// If we have not a session id try to get it and abort if not valid
if( m_SessionId.IsEmpty() && !GetSessionId() )
return false;
PostData = wxT( "s=" ) + m_SessionId + wxT( "&" );
Artist = guURLEncode( cursong->m_ArtistName );
Track = guURLEncode( cursong->m_TrackName );
Album = guURLEncode( cursong->m_AlbumName );
//
PostData += wxString::Format( wxT( "a=%s&t=%s&l=%s&b=%s&n=%s&m=" ),
Artist.c_str(),
Track.c_str(),
( cursong->m_TrackLen ) ?
wxString::Format( wxT( "%u" ), cursong->m_TrackLen ).c_str() :
wxEmptyString,
Album.c_str(),
( cursong->m_TrackNum > 0 ) ?
wxString::Format( wxT( "%u" ), cursong->m_TrackNum ).c_str() :
wxEmptyString
);
//guLogMessage( wxT( "AudioScrobble::NowPlaying : " ) + m_NowPlayUrl + PostData );
Http.AddHeader( wxT( "Content-Type" ), wxT( "application/x-www-form-urlencoded" ) );
if( Http.Post( PostData.ToAscii(), PostData.Length(), m_NowPlayUrl ) )
{
Content = Http.GetResData();
//guLogMessage( wxT( "%i : %s" ), http.GetResponseCode(), Content.c_str() );
if( !Content.IsEmpty() )
{
//guLogMessage( wxT( "AudioScrobble::Response : " ) + Content );
if( Content.Contains( wxT( "OK" ) ) )
{
m_ErrorCode = guAS_ERROR_NOERROR;
return true;
}
else
{
guLogMessage( wxT( "AudioScrobble::NowPlaying : \n%s\n%s" ), m_NowPlayUrl.c_str(), PostData.c_str() );
guLogMessage( wxT( "AudioScrobble::Response : " ) + Content );
ProcessError( Content );
}
}
}
else
{
guLogMessage( wxT( "Error submitting the data to the scrobble server" ) );
}
return false;
}
// -------------------------------------------------------------------------------- //
guLastFMAudioScrobble::guLastFMAudioScrobble( guDbLibrary * db ) :
guAudioScrobbleSender( db, guLASTFM_POST_SERVER )
{
ReadUserConfig();
}
// -------------------------------------------------------------------------------- //
guLastFMAudioScrobble::~guLastFMAudioScrobble()
{
}
// -------------------------------------------------------------------------------- //
void guLastFMAudioScrobble::ReadUserConfig( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
m_UserName = Config->ReadStr( CONFIG_KEY_LASTFM_USERNAME, wxEmptyString, CONFIG_PATH_LASTFM );
m_Password = Config->ReadStr( CONFIG_KEY_LASTFM_PASSWORD, wxEmptyString, CONFIG_PATH_LASTFM );
}
}
// -------------------------------------------------------------------------------- //
guLibreFMAudioScrobble::guLibreFMAudioScrobble( guDbLibrary * db ) :
guAudioScrobbleSender( db, guLIBREFM_POST_SERVER )
{
ReadUserConfig();
}
// -------------------------------------------------------------------------------- //
guLibreFMAudioScrobble::~guLibreFMAudioScrobble()
{
}
// -------------------------------------------------------------------------------- //
void guLibreFMAudioScrobble::ReadUserConfig( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
m_UserName = Config->ReadStr( CONFIG_KEY_LIBREFM_USERNAME, wxEmptyString, CONFIG_PATH_LIBREFM );
m_Password = Config->ReadStr( CONFIG_KEY_LIBREFM_PASSWORD, wxEmptyString, CONFIG_PATH_LIBREFM );
}
}
// -------------------------------------------------------------------------------- //
guAudioScrobble::guAudioScrobble( guDbLibrary * db )
{
m_Db = db;
m_MainFrame = guMainFrame::GetMainFrame();
m_LastFMAudioScrobble = NULL;
m_LibreFMAudioScrobble = NULL;
m_PlayedThread = NULL;
m_NowPlayingInfo = NULL;
m_NowPlayingThread = NULL;
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM ) )
{
m_LastFMAudioScrobble = new guLastFMAudioScrobble( db );
}
if( Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM ) )
{
m_LibreFMAudioScrobble = new guLibreFMAudioScrobble( db );
}
// // Update the MainFrame AudioScrobble Status
// wxCommandEvent event( wxEVT_MENU, ID_AUDIOSCROBBLE_UPDATED );
// event.SetInt( 0 );
// //wxPostEvent( m_MainFrame, event );
// m_MainFrame->AddPendingEvent( event );
// guLogMessage( wxT( "******** Sent the AudioScrobble Update Event ********" ) );
}
// -------------------------------------------------------------------------------- //
guAudioScrobble::~guAudioScrobble()
{
if( m_NowPlayingThread )
{
m_NowPlayingThread->Pause();
m_NowPlayingThread->Delete();
m_NowPlayingThread = NULL;
}
if( m_NowPlayingInfo )
{
delete m_NowPlayingInfo;
}
if( m_PlayedThread )
{
m_PlayedThread->Pause();
m_PlayedThread->Delete();
}
if( m_LastFMAudioScrobble )
delete m_LastFMAudioScrobble;
if( m_LibreFMAudioScrobble )
delete m_LibreFMAudioScrobble;
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobble::SubmitNowPlaying( const guAS_SubmitInfo * curtrack )
{
//guLogMessage( wxT( "guAudioScrobbler:SubmitNowPlaying: %s" ), curtrack->m_TrackName.c_str() );
if( m_LastFMAudioScrobble )
{
m_LastFMAudioScrobble->SubmitNowPlaying( curtrack );
}
if( m_LibreFMAudioScrobble )
{
m_LibreFMAudioScrobble->SubmitNowPlaying( curtrack );
}
int HasError = ( m_LastFMAudioScrobble && m_LastFMAudioScrobble->GetErrorCode() ) ||
( m_LibreFMAudioScrobble && m_LibreFMAudioScrobble->GetErrorCode() );
wxCommandEvent event( wxEVT_MENU, ID_AUDIOSCROBBLE_UPDATED );
event.SetInt( HasError );
wxPostEvent( m_MainFrame, event );
return !HasError;
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobble::SubmitPlayedSongs( const guAS_SubmitInfoArray &playedtracks )
{
int LastFMErrorCode = 0;
int LibreFMErrorCode = 0;
//guLogMessage( wxT( "guAudioScrobbler:SubmitPlayedSongs" ) );
if( m_LastFMAudioScrobble )
{
m_LastFMAudioScrobble->SubmitPlayedSongs( playedtracks );
LastFMErrorCode = m_LastFMAudioScrobble->GetErrorCode();
}
if( m_LibreFMAudioScrobble )
{
m_LibreFMAudioScrobble->SubmitPlayedSongs( playedtracks );
LibreFMErrorCode = m_LibreFMAudioScrobble->GetErrorCode();
}
//guLogMessage( wxT( "ErrorCodes: %i %i" ), LastFMErrorCode, LibreFMErrorCode );
wxCommandEvent event( wxEVT_MENU, ID_AUDIOSCROBBLE_UPDATED );
event.SetInt( ( LastFMErrorCode || LibreFMErrorCode ) );
wxPostEvent( m_MainFrame, event );
return !( LastFMErrorCode || LibreFMErrorCode );
}
// -------------------------------------------------------------------------------- //
void guAudioScrobble::SendPlayedTrack( const guCurrentTrack &track )
{
//guLogMessage( wxT( "guAudioScrobble::SendPlayedTrack" ) );
if( !m_Db->AddCachedPlayedSong( track ) )
guLogError( wxT( "Could not add Song to CachedSongs Database" ) );
if( !m_PlayedThread )
{
m_PlayedThread = new guASPlayedThread( this, m_Db );
if( !m_PlayedThread )
guLogError( wxT( "Could no create the AudioScrobble Played thread" ) );
}
}
// -------------------------------------------------------------------------------- //
void guAudioScrobble::SendNowPlayingTrack( const guCurrentTrack &track )
{
//guLogMessage( wxT( "guAudioScrobble::SendNowPlayingTrack" ) );
wxMutexLocker Lock( m_NowPlayingInfoMutex );
if( m_NowPlayingThread )
{
m_NowPlayingThread->Pause();
m_NowPlayingThread->Delete();
m_NowPlayingThread = NULL;
}
if( m_NowPlayingInfo )
{
guLogMessage( wxT( "Deleted old NowPLayingInfo..." ) );
delete m_NowPlayingInfo;
}
m_NowPlayingInfo = new guAS_SubmitInfo();
m_NowPlayingInfo->m_ArtistName = track.m_ArtistName.IsEmpty() ? wxT( "Unknown" ) : track.m_ArtistName;
m_NowPlayingInfo->m_AlbumName = track.m_AlbumName.IsEmpty() ? wxT( "Unknown" ) : track.m_AlbumName;
m_NowPlayingInfo->m_TrackName = track.m_SongName.IsEmpty() ? wxT( "Unknown" ) : track.m_SongName;
m_NowPlayingInfo->m_TrackLen = track.m_Length / 1000;
m_NowPlayingInfo->m_TrackNum = track.m_Number;
guAS_SubmitInfoArray SubmitInfo;
SubmitInfo = m_Db->GetCachedPlayedSongs( guAS_SUBMITTRACKS );
if( !SubmitInfo.Count() )
{
guLogMessage( wxT( "Now Playing track submit: Now ready to send..." ) );
m_NowPlayingThread = new guASNowPlayingThread( this, m_NowPlayingInfo );
if( !m_NowPlayingThread )
guLogError( wxT( "Could no create the AudioScrobble NowPlaying thread" ) );
m_NowPlayingInfo = NULL;
}
else
{
guLogMessage( wxT( "Now Playing track submit delayed. There are pending tracks to send..." ) );
if( !m_PlayedThread )
{
m_PlayedThread = new guASPlayedThread( this, m_Db );
if( !m_PlayedThread )
guLogError( wxT( "Could no create the AudioScrobble Played thread" ) );
}
}
}
// -------------------------------------------------------------------------------- //
void guAudioScrobble::EndPlayedThread( void )
{
//guLogMessage( wxT( "guAudioScrobble::EndPlayedThread" ) );
wxMutexLocker Lock( m_NowPlayingInfoMutex );
m_PlayedThread = NULL;
if( m_NowPlayingInfo )
{
guLogMessage( wxT( "Now Playing track submit: Now ready to send..." ) );
if( m_NowPlayingThread )
{
m_NowPlayingThread->Pause();
m_NowPlayingThread->Delete();
m_NowPlayingThread = NULL;
}
m_NowPlayingThread = new guASNowPlayingThread( this, m_NowPlayingInfo );
if( !m_NowPlayingThread )
guLogError( wxT( "Could no create the AudioScrobble NowPlaying thread" ) );
m_NowPlayingInfo = NULL;
}
}
// -------------------------------------------------------------------------------- //
void guAudioScrobble::EndNowPlayingThread( void )
{
if( m_NowPlayingThread )
{
//m_NowPlayingThread->Pause();
//m_NowPlayingThread->Delete();
m_NowPlayingThread = NULL;
}
}
// -------------------------------------------------------------------------------- //
void guAudioScrobble::OnConfigUpdated( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM ) )
{
if( !m_LastFMAudioScrobble )
m_LastFMAudioScrobble = new guLastFMAudioScrobble( m_Db );
}
else
{
if( m_LastFMAudioScrobble )
{
delete m_LastFMAudioScrobble;
m_LastFMAudioScrobble = NULL;
}
}
if( Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM ) )
{
if( !m_LibreFMAudioScrobble )
m_LibreFMAudioScrobble = new guLibreFMAudioScrobble( m_Db );
}
else
{
if( m_LibreFMAudioScrobble )
{
delete m_LibreFMAudioScrobble;
m_LibreFMAudioScrobble = NULL;
}
}
if( m_LastFMAudioScrobble )
{
m_LastFMAudioScrobble->OnConfigUpdated();
}
if( m_LibreFMAudioScrobble )
{
m_LibreFMAudioScrobble->OnConfigUpdated();
}
wxCommandEvent event( wxEVT_MENU, ID_AUDIOSCROBBLE_UPDATED );
event.SetInt( !IsOk() );
wxPostEvent( m_MainFrame, event );
}
// -------------------------------------------------------------------------------- //
bool guAudioScrobble::IsOk( void )
{
return ( m_LastFMAudioScrobble && m_LastFMAudioScrobble->IsOk() ) ||
( m_LibreFMAudioScrobble && m_LibreFMAudioScrobble->IsOk() );
}
// -------------------------------------------------------------------------------- //
// guASNowPlayingThread
// -------------------------------------------------------------------------------- //
guASNowPlayingThread::guASNowPlayingThread( guAudioScrobble * audioscrobble,
const guAS_SubmitInfo * currentsong )
{
m_AudioScrobble = audioscrobble;
m_CurrentSong = currentsong;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guASNowPlayingThread::~guASNowPlayingThread()
{
if( m_CurrentSong )
delete m_CurrentSong;
if( !TestDestroy() )
{
m_AudioScrobble->EndNowPlayingThread();
}
}
// -------------------------------------------------------------------------------- //
guASNowPlayingThread::ExitCode guASNowPlayingThread::Entry()
{
int FailCnt = 0;
// While the Thread have not been destroyed
while( !TestDestroy() )
{
// Send the info to lastfm
if( m_AudioScrobble->SubmitNowPlaying( m_CurrentSong ) )
break;
FailCnt++;
if( FailCnt > 2 )
{
break;
}
// If have not been destroyed wait 2 mins between submits.
if( !TestDestroy() )
Sleep( guAS_SUBMIT_RETRY_TIMEOUT ); // Wait 10 secs timeout between each try
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guASPlayedThread
// -------------------------------------------------------------------------------- //
guASPlayedThread::guASPlayedThread( guAudioScrobble * audioscrobble, guDbLibrary * db )
{
m_AudioScrobble = audioscrobble;
m_Db = db;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guASPlayedThread::~guASPlayedThread()
{
if( !TestDestroy() )
{
if( m_AudioScrobble )
m_AudioScrobble->EndPlayedThread();
}
}
// -------------------------------------------------------------------------------- //
guASPlayedThread::ExitCode guASPlayedThread::Entry()
{
guAS_SubmitInfoArray SubmitInfo;
bool Submit = false;
int FailCnt;
// While the Thread have not been destroyed
while( !TestDestroy() )
{
// Query the Database if there are cached played songs to submit
SubmitInfo = m_Db->GetCachedPlayedSongs( guAS_SUBMITTRACKS );
// If we have records to send
if( SubmitInfo.Count() )
{
//guLogMessage( wxT( "**** Trying a AudioScrobble Submit ****" ) );
// We attempt to submit the info every 30 secs
FailCnt = 0;
while( !TestDestroy() && !( Submit = m_AudioScrobble->SubmitPlayedSongs( SubmitInfo ) ) )
{
if( FailCnt++ > 2 )
break;
Sleep( guAS_SUBMIT_RETRY_TIMEOUT ); // Wait 30 Secs between submit attempts
}
// if the submit was ok then delete the songs from cache
if( Submit )
{
m_Db->DeleteCachedPlayedSongs( SubmitInfo );
}
}
else
{
break;
}
Sleep( guAS_SUBMIT_TIMEOUT ); // Wait 30 Secs between submit attempts
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 27,394
|
C++
|
.cpp
| 669
| 33.026906
| 277
| 0.530541
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,572
|
OnlineLinks.cpp
|
anonbeat_guayadeque/src/onlinelinks/OnlineLinks.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "OnlineLinks.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "MainApp.h"
#include "Settings.h"
#include "Utils.h"
#include <wx/uri.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
void AddOnlineLinksMenu( wxMenu * Menu )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem;
if( Menu )
{
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Links = Config->ReadAStr( CONFIG_KEY_SEARCHLINKS_LINK, wxEmptyString, CONFIG_PATH_SEARCHLINKS_LINKS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_SEARCHLINKS_NAME, wxEmptyString, CONFIG_PATH_SEARCHLINKS_NAMES );
int count = Links.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
wxURI Uri( Links[ index ] );
MenuItem = new wxMenuItem( Menu, ID_LINKS_BASE + index, Names[ index ], Links[ index ] );
wxString IconFile = guPATH_LINKICONS + Uri.GetServer() + wxT( ".ico" );
if( wxFileExists( IconFile ) )
{
MenuItem->SetBitmap( wxBitmap( IconFile, wxBITMAP_TYPE_ICO ) );
}
else
{
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_search ) );
}
SubMenu->Append( MenuItem );
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_LINKS, _( "Preferences" ), _( "Add search links in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Links" ) );
}
}
// -------------------------------------------------------------------------------- //
void ExecuteOnlineLink( const int linkid, const wxString &text )
{
int index = linkid - ID_LINKS_BASE;
//guLogMessage( wxT( "ExecuteOnlineLink( %i, '%s' )" ), index, text.c_str() );
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Links = Config->ReadAStr( CONFIG_KEY_SEARCHLINKS_LINK, wxEmptyString, CONFIG_PATH_SEARCHLINKS_LINKS );
if( index >= 0 && ( index < ( int ) Links.Count() ) )
{
wxString SearchLink = Links[ index ];
wxString Lang = Config->ReadStr( CONFIG_KEY_LASTFM_LANGUAGE, wxT( "en" ), CONFIG_PATH_LASTFM );
if( Lang.IsEmpty() )
{
Lang = ( ( guMainApp * ) wxTheApp )->GetLocale()->GetCanonicalName().Mid( 0, 2 );
//guLogMessage( wxT( "Locale: %s" ), ( ( guMainApp * ) wxTheApp )->GetLocale()->GetCanonicalName().c_str() );
}
SearchLink.Replace( guLINKS_LANGUAGE, Lang );
SearchLink.Replace( guLINKS_TEXT, guURLEncode( text ) );
guWebExecute( SearchLink );
}
else
{
guLogMessage( wxT( "Online Link out of rante %i" ), index );
}
}
}
// -------------------------------------------------------------------------------- //
| 4,126
|
C++
|
.cpp
| 96
| 36.40625
| 133
| 0.5474
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,573
|
Accelerators.cpp
|
anonbeat_guayadeque/src/misc/Accelerators.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Accelerators.h"
#include "Utils.h"
#include "Config.h"
#include "EventCommandIds.h"
namespace Guayadeque {
// Build the Accelerators
static wxArrayInt guAccelCmdIds;
static wxArrayInt guAccelKeys;
// -------------------------------------------------------------------------------- //
void guAccelInit( void )
{
if( !guAccelCmdIds.Count() )
{
guAccelCmdIds.Add( ID_MENU_LIBRARY_ADD_PATH );
guAccelCmdIds.Add( ID_MAINFRAME_SETAUDIOSCROBBLE );
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_CLEAR );
guAccelCmdIds.Add( ID_MENU_VIEW_CLOSEWINDOW );
guAccelCmdIds.Add( ID_MENU_COMMUNITY );
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
guAccelCmdIds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
guAccelCmdIds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
guAccelCmdIds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
//
guAccelCmdIds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
guAccelCmdIds.Add( ID_MENU_VIEW_FULLSCREEN );
guAccelCmdIds.Add( ID_MAINFRAME_SETFORCEGAPLESS );
guAccelCmdIds.Add( ID_MENU_HELP );
guAccelCmdIds.Add( ID_TRACKS_PLAY );
guAccelCmdIds.Add( ID_TRACKS_PLAYALL );
guAccelCmdIds.Add( ID_PLAYERPANEL_PLAY );
guAccelCmdIds.Add( ID_MENU_PLAY_STREAM );
guAccelCmdIds.Add( ID_MENU_PREFERENCES );
guAccelCmdIds.Add( ID_MENU_QUIT );
//
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_RANDOMPLAY );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_0 );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_1 );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_2 );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_3 );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_4 );
guAccelCmdIds.Add( ID_PLAYERPANEL_SETRATING_5 );
guAccelCmdIds.Add( ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST );
guAccelCmdIds.Add( ID_PLAYER_PLAYMODE_REPEAT_TRACK );
guAccelCmdIds.Add( ID_MENU_LAYOUT_CREATE );
//
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_SAVE );
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_SEARCH );
guAccelCmdIds.Add( ID_MENU_VIEW_ALBUMBROWSER );
guAccelCmdIds.Add( ID_MENU_VIEW_MAIN_SHOWCOVER );
guAccelCmdIds.Add( ID_MENU_VIEW_PLAYER_PLAYLIST );
guAccelCmdIds.Add( ID_MENU_VIEW_FILEBROWSER );
guAccelCmdIds.Add( ID_MENU_VIEW_PLAYER_FILTERS );
guAccelCmdIds.Add( ID_MENU_VIEW_LASTFM );
guAccelCmdIds.Add( ID_MENU_VIEW_LIBRARY );
guAccelCmdIds.Add( ID_MENU_VIEW_LYRICS );
//
guAccelCmdIds.Add( ID_MENU_VIEW_RADIO );
guAccelCmdIds.Add( ID_MENU_VIEW_PLAYLISTS );
guAccelCmdIds.Add( ID_MENU_VIEW_PODCASTS );
guAccelCmdIds.Add( ID_MENU_VIEW_MAIN_LOCATIONS );
guAccelCmdIds.Add( ID_MENU_VIEW_STATUSBAR );
guAccelCmdIds.Add( ID_MENU_VIEW_PLAYER_VUMETERS );
guAccelCmdIds.Add( ID_PLAYERPANEL_NEXTTRACK );
guAccelCmdIds.Add( ID_PLAYERPANEL_NEXTALBUM );
guAccelCmdIds.Add( ID_PLAYERPANEL_PREVTRACK );
guAccelCmdIds.Add( ID_PLAYERPANEL_PREVALBUM );
//
guAccelCmdIds.Add( ID_PLAYER_PLAYMODE_SMART );
guAccelCmdIds.Add( ID_PLAYERPANEL_STOP );
guAccelCmdIds.Add( ID_PLAYER_PLAYLIST_STOP_ATEND );
guAccelCmdIds.Add( ID_MENU_UPDATE_COVERS );
guAccelCmdIds.Add( ID_MENU_UPDATE_LIBRARY );
guAccelCmdIds.Add( ID_MENU_UPDATE_LIBRARYFORCED );
guAccelCmdIds.Add( ID_MENU_UPDATE_PODCASTS );
guAccelCmdIds.Add( ID_MENU_VOLUME_DOWN );
guAccelCmdIds.Add( ID_MENU_VOLUME_UP );
}
guAccelOnConfigUpdated();
}
// -------------------------------------------------------------------------------- //
int guAccelGetActionNames( wxArrayString &actionnames )
{
actionnames.Add( _( "Add Folder" ) );
actionnames.Add( _( "Audio Scrobbling" ) );
actionnames.Add( _( "Clear Playlist" ) );
actionnames.Add( _( "Close Window" ) );
actionnames.Add( _( "Community Forums" ) );
actionnames.Add( _( "Edit Labels" ) );
actionnames.Add( _( "Edit Tracks" ) );
actionnames.Add( _( "Enqueue" ) );
actionnames.Add( _( "Enqueue After Track" ) );
actionnames.Add( _( "Enqueue After Album" ) );
//
actionnames.Add( _( "Enqueue After Artist" ) );
actionnames.Add( _( "Full Screen" ) );
actionnames.Add( _( "Gapless/Crossfading" ) );
actionnames.Add( _( "Help" ) );
actionnames.Add( _( "Play" ) );
actionnames.Add( _( "Play All" ) );
actionnames.Add( _( "Play/Pause" ) );
actionnames.Add( _( "Play Stream" ) );
actionnames.Add( _( "Preferences" ) );
actionnames.Add( _( "Quit" ) );
//
actionnames.Add( _( "Randomize Playlist" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ☆☆☆☆☆" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ★☆☆☆☆" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ★★☆☆☆" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ★★★☆☆" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ★★★★☆" ) );
actionnames.Add( wxString( _( "Rating" ) ) + wxT( " ★★★★★" ) );
actionnames.Add( _( "Repeat All Tracks" ) );
actionnames.Add( _( "Repeat Current Track" ) );
actionnames.Add( _( "Save Layout" ) );
//
actionnames.Add( _( "Save to Playlist" ) );
actionnames.Add( _( "Search" ) );
actionnames.Add( _( "Show Browser" ) );
actionnames.Add( _( "Show Covers" ) );
actionnames.Add( _( "Show Playlist" ) );
actionnames.Add( _( "Show Files" ) );
actionnames.Add( _( "Show Filters" ) );
actionnames.Add( _( "Show Last.fm" ) );
actionnames.Add( _( "Show Library" ) );
actionnames.Add( _( "Show Lyrics" ) );
//
actionnames.Add( _( "Show Radio" ) );
actionnames.Add( _( "Show Playlists" ) );
actionnames.Add( _( "Show Podcasts" ) );
actionnames.Add( _( "Show Sources" ) );
actionnames.Add( _( "Show Status Bar" ) );
actionnames.Add( _( "Show VU Meters" ) );
actionnames.Add( _( "Skip Next" ) );
actionnames.Add( _( "Skip Next Album" ) );
actionnames.Add( _( "Skip Previous" ) );
actionnames.Add( _( "Skip Previous Album" ) );
//
actionnames.Add( _( "Smart Play" ) );
actionnames.Add( _( "Stop" ) );
actionnames.Add( _( "Stop at End" ) );
actionnames.Add( _( "Update Covers" ) );
actionnames.Add( _( "Update" ) );
actionnames.Add( _( "Update (Forced)" ) );
actionnames.Add( _( "Update Podcasts" ) );
actionnames.Add( _( "Volume Down" ) );
actionnames.Add( _( "Volume Up" ) );
return actionnames.Count();
}
// -------------------------------------------------------------------------------- //
int guAccelGetDefaultKeys( wxArrayInt &accelkeys )
{
accelkeys.Add( 131140 );
accelkeys.Add( 131156 );
accelkeys.Add( 131199 );
accelkeys.Add( 131159 );
accelkeys.Add( 262484 );
accelkeys.Add( 65612 );
accelkeys.Add( 65605 );
accelkeys.Add( 131085 );
accelkeys.Add( 393229 );
accelkeys.Add( 65549 );
//
accelkeys.Add( 327693 );
accelkeys.Add( 350 );
accelkeys.Add( 131143 );
accelkeys.Add( 340 );
accelkeys.Add( 13 );
accelkeys.Add( 196621 );
accelkeys.Add( 65616 );
accelkeys.Add( 131151 );
accelkeys.Add( 344 );
accelkeys.Add( 131153 );
//
accelkeys.Add( 196690 );
accelkeys.Add( 65584 );
accelkeys.Add( 65585 );
accelkeys.Add( 65586 );
accelkeys.Add( 65587 );
accelkeys.Add( 65588 );
accelkeys.Add( 65589 );
accelkeys.Add( 342 );
accelkeys.Add( 262486 );
accelkeys.Add( 343 );
//
accelkeys.Add( 131155 );
accelkeys.Add( 131142 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
//
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 0 );
accelkeys.Add( 351 );
accelkeys.Add( 0 );
accelkeys.Add( 347 );
accelkeys.Add( 262491 );
accelkeys.Add( 346 );
accelkeys.Add( 262490 );
//
accelkeys.Add( 341 );
accelkeys.Add( 65619 );
accelkeys.Add( 327763 );
accelkeys.Add( 65603 );
accelkeys.Add( 196693 );
accelkeys.Add( 458837 );
accelkeys.Add( 131152 );
accelkeys.Add( 65604 );
accelkeys.Add( 65621 );
return accelkeys.Count();
}
// -------------------------------------------------------------------------------- //
void guAccelOnConfigUpdated( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
guAccelKeys = Config->ReadANum( CONFIG_KEY_ACCELERATORS_ACCELKEY, 0, CONFIG_PATH_ACCELERATORS );
if( guAccelKeys.Count() == 0 )
{
guAccelGetDefaultKeys( guAccelKeys );
}
while( guAccelKeys.Count() < guAccelCmdIds.Count() )
guAccelKeys.Add( 0 );
}
// -------------------------------------------------------------------------------- //
wxString guAccelGetKeyCodeString( const int keycode )
{
wxString KeyStr;
if( keycode )
{
int Modifier = keycode >> 16;
int KeyCode = keycode & 0xFFFF;
if( Modifier )
{
if( Modifier & wxMOD_SHIFT )
{
KeyStr += wxString( _( "Shift" ) ) + wxT( "-" );
}
if( Modifier & wxMOD_CONTROL )
{
KeyStr += wxString( _( "Ctrl" ) ) + wxT( "-" );
}
if( Modifier & wxMOD_ALT )
{
KeyStr += wxString( _( "Alt" ) ) + wxT( "-" );
}
if( Modifier & wxMOD_META )
{
KeyStr += wxString( _( "Meta" ) ) + wxT( "-" );
}
}
switch( KeyCode )
{
case WXK_NUMPAD0 :
case WXK_NUMPAD1 :
case WXK_NUMPAD2 :
case WXK_NUMPAD3 :
case WXK_NUMPAD4 :
case WXK_NUMPAD5 :
case WXK_NUMPAD6 :
case WXK_NUMPAD7 :
case WXK_NUMPAD8 :
case WXK_NUMPAD9 : KeyStr += wxString::Format( wxT( "%d" ), KeyCode - WXK_NUMPAD0 ); break;
case WXK_BACK : KeyStr += _( "Back" ); break;
case WXK_ESCAPE : KeyStr += _( "Escape" ); break;
case WXK_SPACE :
case WXK_NUMPAD_SPACE : KeyStr += _( "Space" ); break;
case WXK_TAB :
case WXK_NUMPAD_TAB : KeyStr += _( "Tab" ); break;
case WXK_RETURN : KeyStr += _( "Return" ); break;
case WXK_NUMPAD_ENTER : KeyStr += _( "Enter" ); break;
case WXK_NUMPAD_F1 :
case WXK_NUMPAD_F2 :
case WXK_NUMPAD_F3 :
case WXK_NUMPAD_F4 : KeyStr += wxString::Format( wxT( "F%d" ), KeyCode- WXK_NUMPAD_F1 + 1 ); break;
case WXK_F1 :
case WXK_F2 :
case WXK_F3 :
case WXK_F4 :
case WXK_F5 :
case WXK_F6 :
case WXK_F7 :
case WXK_F8 :
case WXK_F9 :
case WXK_F10 :
case WXK_F11 :
case WXK_F12 :
case WXK_F13 :
case WXK_F14 :
case WXK_F15 :
case WXK_F16 :
case WXK_F17 :
case WXK_F18 :
case WXK_F19 :
case WXK_F20 :
case WXK_F21 :
case WXK_F22 :
case WXK_F23 :
case WXK_F24 : KeyStr += wxString::Format( wxT( "F%d" ), KeyCode - WXK_F1 + 1 ); break;
case WXK_LEFT :
case WXK_NUMPAD_LEFT : KeyStr += _( "Left" ); break;
case WXK_UP :
case WXK_NUMPAD_UP : KeyStr += _( "Up" ); break;
case WXK_RIGHT :
case WXK_NUMPAD_RIGHT : KeyStr += _( "Right" ); break;
case WXK_DOWN:
case WXK_NUMPAD_DOWN : KeyStr += _( "Down" ); break;
case WXK_NUMPAD_HOME : KeyStr += _( "Home" ); break;
#if not wxCHECK_VERSION(2, 8, 0)
case WXK_PRIOR:
case WXK_NUMPAD_PRIOR : KeyStr += _( "Page Up" ); break;
case WXK_NEXT:
case WXK_NUMPAD_NEXT : KeyStr += _( "Page Down" ); break;
#endif
case WXK_PAGEUP :
case WXK_NUMPAD_PAGEUP : KeyStr += _( "Page Up"); break;
case WXK_PAGEDOWN :
case WXK_NUMPAD_PAGEDOWN : KeyStr += _( "Page Down" ); break;
case WXK_END :
case WXK_NUMPAD_END : KeyStr += _( "End" ); break;
case WXK_NUMPAD_BEGIN : KeyStr += _( "Begin" ); break;
case WXK_NUMPAD_INSERT : KeyStr += _( "Insert" ); break;
case WXK_DELETE:
case WXK_NUMPAD_DELETE : KeyStr += _( "Delete" ); break;
case WXK_NUMPAD_EQUAL : KeyStr += wxT( "=" ); break;
case WXK_MULTIPLY:
case WXK_NUMPAD_MULTIPLY : KeyStr += wxT( "*" ); break;
case WXK_ADD :
case WXK_NUMPAD_ADD : KeyStr += wxT( "+" ); break;
case WXK_SEPARATOR:
case WXK_NUMPAD_SEPARATOR : KeyStr += _( "Separator" ); break;
case WXK_SUBTRACT:
case WXK_NUMPAD_SUBTRACT : KeyStr += wxT( "-" ); break;
case WXK_DECIMAL :
case WXK_NUMPAD_DECIMAL : KeyStr += wxT( "." ); break;
case WXK_DIVIDE :
case WXK_NUMPAD_DIVIDE : KeyStr += wxT( "/" ); break;
case WXK_SELECT : KeyStr += _( "Select" ); break;
case WXK_PRINT : KeyStr += _( "Print" ); break;
case WXK_EXECUTE : KeyStr += _( "Execute" ); break;
case WXK_SNAPSHOT : KeyStr += _( "Snapshot" ); break;
case WXK_INSERT : KeyStr += _( "Insert" ); break;
case WXK_HELP : KeyStr += _( "Help" ); break;
case WXK_CANCEL : KeyStr += _( "Cancel" ); break;
case WXK_MENU : KeyStr += _( "Menu" ); break;
case WXK_CAPITAL : KeyStr += _( "Capital" ); break;
case WXK_HOME : KeyStr += _( "Home" ); break;
default :
if( wxIsalnum( KeyCode ) || wxIsprint( KeyCode ) ) // ASCII chars...
{
KeyStr += ( wxChar ) KeyCode;
break;
}
}
}
return KeyStr;
}
// -------------------------------------------------------------------------------- //
wxString guAccelGetKeyCodeMenuString( const int keycode )
{
wxString KeyStr;
if( keycode )
{
KeyStr += wxT( "\t" );
int Modifier = keycode >> 16;
int KeyCode = keycode & 0xFFFF;
if( Modifier )
{
if( Modifier & wxMOD_SHIFT )
{
KeyStr += wxT( "Shift-" );
}
if( Modifier & wxMOD_CONTROL )
{
KeyStr += wxT( "Ctrl-" );
}
if( Modifier & wxMOD_ALT )
{
KeyStr += wxT( "Alt-" );
}
if( Modifier & wxMOD_META )
{
KeyStr += wxT( "Meta-" );
}
}
switch( KeyCode )
{
case WXK_NUMPAD0 :
case WXK_NUMPAD1 :
case WXK_NUMPAD2 :
case WXK_NUMPAD3 :
case WXK_NUMPAD4 :
case WXK_NUMPAD5 :
case WXK_NUMPAD6 :
case WXK_NUMPAD7 :
case WXK_NUMPAD8 :
case WXK_NUMPAD9 : KeyStr += wxString::Format( wxT( "%d" ), KeyCode - WXK_NUMPAD0 ); break;
case WXK_BACK : KeyStr += wxT( "Back" ); break;
case WXK_ESCAPE : KeyStr += wxT( "Escape" ); break;
case WXK_SPACE :
case WXK_NUMPAD_SPACE : KeyStr += wxT( "Space" ); break;
case WXK_TAB :
case WXK_NUMPAD_TAB : KeyStr += wxT( "Tab" ); break;
case WXK_RETURN : KeyStr += wxT( "Return" ); break;
case WXK_NUMPAD_ENTER : KeyStr += wxT( "Enter" ); break;
case WXK_NUMPAD_F1 :
case WXK_NUMPAD_F2 :
case WXK_NUMPAD_F3 :
case WXK_NUMPAD_F4 : KeyStr += wxString::Format( wxT( "F%d" ), KeyCode- WXK_NUMPAD_F1 + 1 ); break;
case WXK_F1 :
case WXK_F2 :
case WXK_F3 :
case WXK_F4 :
case WXK_F5 :
case WXK_F6 :
case WXK_F7 :
case WXK_F8 :
case WXK_F9 :
case WXK_F10 :
case WXK_F11 :
case WXK_F12 :
case WXK_F13 :
case WXK_F14 :
case WXK_F15 :
case WXK_F16 :
case WXK_F17 :
case WXK_F18 :
case WXK_F19 :
case WXK_F20 :
case WXK_F21 :
case WXK_F22 :
case WXK_F23 :
case WXK_F24 : KeyStr += wxString::Format( wxT( "F%d" ), KeyCode - WXK_F1 + 1 ); break;
case WXK_LEFT :
case WXK_NUMPAD_LEFT : KeyStr += wxT( "Left" ); break;
case WXK_UP :
case WXK_NUMPAD_UP : KeyStr += wxT( "Up" ); break;
case WXK_RIGHT :
case WXK_NUMPAD_RIGHT : KeyStr += wxT( "Right" ); break;
case WXK_DOWN:
case WXK_NUMPAD_DOWN : KeyStr += wxT( "Down" ); break;
case WXK_NUMPAD_HOME : KeyStr += wxT( "Home" ); break;
#if not wxCHECK_VERSION(2, 8, 0)
case WXK_PRIOR:
case WXK_NUMPAD_PRIOR : KeyStr += wxT( "PgUp" ); break;
case WXK_NEXT:
case WXK_NUMPAD_NEXT : KeyStr += wxT( "PgDown" ); break;
#endif
case WXK_PAGEUP :
case WXK_NUMPAD_PAGEUP : KeyStr += wxT( "PgUp"); break;
case WXK_PAGEDOWN :
case WXK_NUMPAD_PAGEDOWN : KeyStr += wxT( "PgDown" ); break;
case WXK_END :
case WXK_NUMPAD_END : KeyStr += wxT( "End" ); break;
case WXK_NUMPAD_BEGIN : KeyStr += wxT( "Begin" ); break;
case WXK_NUMPAD_INSERT : KeyStr += wxT( "Insert" ); break;
case WXK_DELETE:
case WXK_NUMPAD_DELETE : KeyStr += wxT( "Delete" ); break;
case WXK_NUMPAD_EQUAL : KeyStr += wxT( "=" ); break;
case WXK_MULTIPLY:
case WXK_NUMPAD_MULTIPLY : KeyStr += wxT( "*" ); break;
case WXK_ADD :
case WXK_NUMPAD_ADD : KeyStr += wxT( "+" ); break;
case WXK_SEPARATOR:
case WXK_NUMPAD_SEPARATOR : KeyStr += wxT( "Separator" ); break;
case WXK_SUBTRACT:
case WXK_NUMPAD_SUBTRACT : KeyStr += wxT( "-" ); break;
case WXK_DECIMAL :
case WXK_NUMPAD_DECIMAL : KeyStr += wxT( "." ); break;
case WXK_DIVIDE :
case WXK_NUMPAD_DIVIDE : KeyStr += wxT( "/" ); break;
case WXK_SELECT : KeyStr += wxT( "Select" ); break;
case WXK_PRINT : KeyStr += wxT( "Print" ); break;
case WXK_EXECUTE : KeyStr += wxT( "Execute" ); break;
case WXK_SNAPSHOT : KeyStr += wxT( "Snapshot" ); break;
case WXK_INSERT : KeyStr += wxT( "Insert" ); break;
case WXK_HELP : KeyStr += wxT( "Help" ); break;
case WXK_CANCEL : KeyStr += wxT( "Cancel" ); break;
case WXK_MENU : KeyStr += wxT( "Menu" ); break;
case WXK_CAPITAL : KeyStr += wxT( "Capital" ); break;
case WXK_HOME : KeyStr += wxT( "Home" ); break;
default :
if( wxIsalnum( KeyCode ) || wxIsprint( KeyCode ) ) // ASCII chars...
{
KeyStr += ( wxChar ) KeyCode;
break;
}
}
}
return KeyStr;
}
// -------------------------------------------------------------------------------- //
wxString guAccelGetCommandKeyCodeString( const int cmd )
{
int CmdIndex = guAccelCmdIds.Index( cmd );
if( CmdIndex != wxNOT_FOUND )
{
try {
return guAccelGetKeyCodeMenuString( guAccelKeys[ CmdIndex ] );
}
catch(...)
{
guLogError( wxT( "Adding menu accelerator for cmd %i at pos %i" ), cmd, CmdIndex );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
int guAccelGetCommandKeyCode( const int cmd )
{
int CmdIndex = guAccelCmdIds.Index( cmd );
if( CmdIndex != wxNOT_FOUND )
{
return guAccelKeys[ CmdIndex ];
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guAccelDoAcceleratorTable( const wxArrayInt &aliascmds, const wxArrayInt &realcmds, wxAcceleratorTable &acceltable )
{
wxAcceleratorEntry AccelEntries[ 20 ];
int EntryCount = 0;
int Count = aliascmds.Count();
for( int Index = 0; Index < Count; Index++ )
{
int AccelKeyCode = guAccelGetCommandKeyCode( aliascmds[ Index ] );
if( AccelKeyCode )
{
//guLogMessage( wxT( "Creating Accelerator %i) %04X %04X %i '%s'" ), Index, AccelKeyCode >> 16, AccelKeyCode & 0xFFFF, AccelKeyCode & 0xFFFF, guAccelGetKeyCodeString( AccelKeyCode ).c_str() );
AccelEntries[ EntryCount++ ].Set( AccelKeyCode >> 16, AccelKeyCode & 0xFFFF, realcmds[ Index ] );
}
}
if( EntryCount )
{
acceltable = wxAcceleratorTable( EntryCount, AccelEntries );
}
return EntryCount;
}
}
// -------------------------------------------------------------------------------- //
| 22,962
|
C++
|
.cpp
| 567
| 31.876543
| 206
| 0.519331
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,574
|
TimeLine.cpp
|
anonbeat_guayadeque/src/misc/TimeLine.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// Bassed on the QTimeLine class from QT
// -------------------------------------------------------------------------------- //
#include "TimeLine.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
static const float pi = 3.14159265359;
static const float halfPi = pi / 2.0;
// -------------------------------------------------------------------------------- //
static float inline guSinProgress( float value )
{
return ::sin( ( value * pi ) - halfPi ) / 2.0 + 0.5;
}
// -------------------------------------------------------------------------------- //
static float inline guSmoothBeginEndMixFactor( float value )
{
return wxMin( wxMax( ( 1.0 - value * 2.0 + 0.3 ), 0.0 ), 1.0 );
}
// -------------------------------------------------------------------------------- //
guTimeLine::guTimeLine( int duration, wxEvtHandler * parent )
{
m_Duration = duration;
m_Parent = parent;
m_StartTime = 0;
m_StartFrame = 0;
m_EndFrame = 0;
m_UpdateInterval = ( 1000 / 25 );
m_TotalLoopCount = 1;
m_CurrentLoopCount = 0;
m_TimerId = 0;
m_Direction = guTimeLine::Forward;
m_CurveShape = guTimeLine::EaseInOutCurve;
m_State = guTimeLine::NotRunning;
m_CurrentTime = wxNOT_FOUND;
SetCurrentTime( 0 );
}
// -------------------------------------------------------------------------------- //
guTimeLine::~guTimeLine()
{
if( m_TimerId )
TimerDestroy(); //g_source_remove( m_TimerId );
m_TimerId = 0;
}
// -------------------------------------------------------------------------------- //
void guTimeLine::ChangeCurrentTime( const int msecs )
{
//guLogMessage( wxT( "///////////////////////// %i - %i - %i" ), m_Duration, msecs, m_CurrentTime );
if( msecs == m_CurrentTime )
return;
float LastValue = CurrentValue();
int LastFrame = CurrentFrame();
m_CurrentTime = msecs;
while( m_CurrentTime < 0 )
m_CurrentTime += m_Duration;
bool Looped = ( msecs < 0 || msecs > m_Duration );
m_CurrentTime %= ( m_Duration + 1 );
if( Looped )
++m_CurrentLoopCount;
bool Ended = false;
if( m_TotalLoopCount && Looped && m_CurrentLoopCount >= m_TotalLoopCount )
{
Ended = true;
m_CurrentTime = ( m_Direction == guTimeLine::Backward ) ? 0 : m_Duration;
}
if( LastValue != CurrentValue() )
{
ValueChanged( CurrentValue() );
//guLogMessage( wxT( "************** Value: %0.2f" ), CurrentValue() );
}
if( LastFrame != CurrentFrame() )
{
FrameChanged( CurrentFrame() );
//guLogMessage( wxT( "************** Frame: %i" ), CurrentFrame() );
}
if( Ended )
{
Stop();
Finished();
}
}
// -------------------------------------------------------------------------------- //
void guTimeLine::SetDirection( guDirection direction )
{
m_Direction = direction;
m_StartTime = m_CurrentTime;
//m_Timer.Start();
}
// -------------------------------------------------------------------------------- //
void guTimeLine::SetCurrentTime( const int msec )
{
m_StartTime = 0;
ChangeCurrentTime( msec );
}
// -------------------------------------------------------------------------------- //
float guTimeLine::ValueForTime( int msec )
{
msec = wxMin( wxMax( msec, 0 ), m_Duration );
// Simple linear interpolation
float Value = msec / float( m_Duration );
switch( m_CurveShape )
{
case EaseInOutCurve :
Value = guSinProgress( Value );
break;
// SmoothBegin blends Smooth and Linear Interpolation.
// Progress 0 - 0.3 : Smooth only
// Progress 0.3 - ~ 0.5 : Mix of Smooth and Linear
// Progress ~ 0.5 - 1 : Linear only
case EaseInCurve :
{
const float SinProgress = guSinProgress( Value );
const float LinearProgress = Value;
const float Mix = guSmoothBeginEndMixFactor( Value );
Value = SinProgress * Mix + LinearProgress * ( 1.0 - Mix );
break;
}
case EaseOutCurve:
{
const float SinProgress = guSinProgress( Value );
const float LinearProgress = Value;
const float Mix = guSmoothBeginEndMixFactor( 1.0 - Value );
Value = SinProgress * Mix + LinearProgress * ( 1.0 - Mix );
break;
}
case SineCurve:
Value = ( ::sin( ( ( msec * pi * 2 ) / m_Duration ) - pi / 2.0 ) + 1.0 ) / 2.0;
break;
default:
break;
}
return Value;
}
// -------------------------------------------------------------------------------- //
static bool TimerUpdated( guTimeLine * timeline )
{
timeline->TimerEvent();
return true;
}
// -------------------------------------------------------------------------------- //
void guTimeLine::TimerEvent( void )
{
ChangeCurrentTime( m_Direction == Forward ? m_CurrentTime + m_UpdateInterval : m_CurrentTime - m_UpdateInterval );
}
// -------------------------------------------------------------------------------- //
int guTimeLine::TimerCreate( void )
{
return g_timeout_add( m_UpdateInterval, GSourceFunc( TimerUpdated ), this );
}
// -------------------------------------------------------------------------------- //
void guTimeLine::Start( void )
{
if( m_TimerId )
{
guLogWarning( wxT( "guTimeLine::Start: already running" ) );
return;
}
if( m_CurrentTime == m_Duration && m_Direction == guTimeLine::Forward )
{
m_CurrentTime = 0;
}
else if( m_CurrentTime == 0 && m_Direction == guTimeLine::Backward )
{
m_CurrentTime = m_Duration;
}
//m_TimerId = g_timeout_add( m_UpdateInterval, GSourceFunc( TimerUpdated ), this );
m_TimerId = TimerCreate();
m_StartTime = m_CurrentTime;
SetState( guTimeLine::Running );
}
// -------------------------------------------------------------------------------- //
void guTimeLine::Stop( void )
{
if( m_TimerId )
TimerDestroy(); //g_source_remove( m_TimerId );
m_TimerId = 0;
SetState( guTimeLine::NotRunning );
}
// -------------------------------------------------------------------------------- //
void guTimeLine::SetPaused( const bool paused )
{
if( m_State == NotRunning )
{
guLogWarning( wxT( "guTimeLine::SetPaused: Not running" ) );
return;
}
if( paused && m_State != Paused )
{
m_StartTime = m_CurrentTime;
TimerDestroy(); //g_source_remove( m_TimerId );
m_TimerId = 0;
SetState( guTimeLine::Paused );
}
else if( !paused && m_State == Paused )
{
//m_TimerId = g_timeout_add( m_UpdateInterval, GSourceFunc( TimerUpdated ), this );
m_TimerId = TimerCreate();
SetState( guTimeLine::Running );
}
}
// -------------------------------------------------------------------------------- //
void guTimeLine::ValueChanged( float value )
{
guLogMessage( wxT( "guTimeLine::ValueChanged to %0.2f" ), value );
}
// -------------------------------------------------------------------------------- //
void guTimeLine::FrameChanged( int frame )
{
}
// -------------------------------------------------------------------------------- //
void guTimeLine::StateChanged( guState state )
{
}
// -------------------------------------------------------------------------------- //
void guTimeLine::Finished( void )
{
}
}
// -------------------------------------------------------------------------------- //
| 8,607
|
C++
|
.cpp
| 238
| 31.462185
| 118
| 0.480058
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,575
|
MD5.cpp
|
anonbeat_guayadeque/src/misc/MD5.cpp
|
// -------------------------------------------------------------------------------- //
//
// Name: md5.cpp
// Author: Kai Krahn
// Created: 11.11.07 12:35
// Description: wxWidgets md5 implementation
//
// This code implements the MD5 message-digest algorithm.
// The algorithm is due to Ron Rivest. This code is based on the code
// written by Colin Plumb in 1993, no copyright is claimed.
// This code is in the public domain; do with it what you wish.
//
// This version implements the MD5 algorithm for the free GUI toolkit wxWidgets.
// Basic functionality, like MD5 hash creation out of strings and files, or
// to verify strings and files against a given MD5 hash, was added
// by Kai Krahn.
//
// This code is provided "as is" and comes without any warranty!
// -------------------------------------------------------------------------------- //
#include <wx/sstream.h>
#include <wx/wfstream.h>
#include <wx/filename.h>
#include <memory.h> /* for memcpy() */
#include "MD5.h"
#ifndef HIGHFIRST
#ifdef wxBYTE_ORDER
#if wxBYTE_ORDER == wxBIG_ENDIAN
#define HIGHFIRST
#endif
#endif
#endif
//---------------------------------------------------------------------------
#ifndef HIGHFIRST
#define byteReverse( buf, len ) /* Nothing */
#else
// -------------------------------------------------------------------------------- //
void byteReverse( unsigned char * buf, unsigned longs )
{
uint32 t;
do {
t = ( uint32 ) ( ( unsigned ) buf[ 3 ] << 8 | buf[ 2 ] ) << 16 |
( ( unsigned ) buf[ 1 ] << 8 | buf[ 0 ] );
*( uint32 * ) buf = t;
buf += 4;
} while ( --longs );
}
#endif
// -------------------------------------------------------------------------------- //
guMD5CTX::guMD5CTX()
{
Init();
}
// -------------------------------------------------------------------------------- //
void guMD5CTX::Init()
{
m_State[ 0 ] = 0x67452301;
m_State[ 1 ] = 0xefcdab89;
m_State[ 2 ] = 0x98badcfe;
m_State[ 3 ] = 0x10325476;
m_Count[ 0 ] = 0;
m_Count[ 1 ] = 0;
}
// -------------------------------------------------------------------------------- //
void guMD5CTX::Update( const unsigned char * buf, unsigned len )
{
uint32 t;
/* Update bitcount */
t = m_Count[ 0 ];
if( ( m_Count[ 0 ] = t + ( ( uint32 ) len << 3 ) ) < t )
m_Count[ 1 ]++; /* Carry from low to high */
m_Count[ 1 ] += len >> 29;
t = ( t >> 3 ) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if( t )
{
unsigned char * p = ( unsigned char * ) m_Buffer + t;
t = 64 - t;
if( len < t )
{
memcpy( p, buf, len );
return;
}
memcpy( p, buf, t );
byteReverse( m_Buffer, 16 );
Transform( ( uint32 * ) m_Buffer );
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while( len >= 64 )
{
memcpy( m_Buffer, buf, 64 );
byteReverse( m_Buffer, 16 );
Transform( ( uint32 * ) m_Buffer );
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy( m_Buffer, buf, len );
}
// -------------------------------------------------------------------------------- //
void guMD5CTX::Final( unsigned char digest[ 16 ] )
{
unsigned Cnt;
unsigned char *p;
/* Compute number of bytes mod 64 */
Cnt = ( m_Count[ 0 ] >> 3 ) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = m_Buffer + Cnt;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
Cnt = 64 - 1 - Cnt;
/* Pad out to 56 mod 64 */
if( Cnt < 8 )
{
/* Two lots of padding: Pad the first block to 64 bytes */
memset( p, 0, Cnt );
byteReverse( m_Buffer, 16 );
Transform( ( uint32 * ) m_Buffer );
/* Now fill the next block with 56 bytes */
memset( m_Buffer, 0, 56 );
}
else
{
/* Pad block to 56 bytes */
memset( p, 0, Cnt - 8 );
}
byteReverse( m_Buffer, 14 );
/* Append length in bits and transform */
( ( uint32 * ) m_Buffer )[ 14 ] = m_Count[ 0 ];
( ( uint32 * ) m_Buffer )[ 15 ] = m_Count[ 1 ];
Transform( ( uint32 * ) m_Buffer );
byteReverse( ( unsigned char * ) m_State, 4 );
memcpy( digest, m_State, 16 );
//memset( ctx, 0, sizeof( ctx ) ); /* In case it's sensitive */
}
// -------------------------------------------------------------------------------- //
/** The four core functions - F1 is optimized somewhat */
/* #define F1( x, y, z ) ( x & y | ~x & z ) */
#define F1( x, y, z ) ( z ^ ( x & ( y ^ z ) ) )
#define F2( x, y, z ) F1( z, x, y )
#define F3( x, y, z ) ( x ^ y ^ z )
#define F4( x, y, z ) ( y ^ ( x | ~z ) )
/** This is the central step in the MD5 algorithm. */
#define MD5STEP( f, w, x, y, z, data, s ) \
( w += f( x, y, z ) + data, w = w<<s | w>>( 32-s ), w += x )
// -------------------------------------------------------------------------------- //
void guMD5CTX::Transform( uint32 in[ 16 ] )
{
register uint32 a, b, c, d;
a = m_State[ 0 ];
b = m_State[ 1 ];
c = m_State[ 2 ];
d = m_State[ 3 ];
MD5STEP( F1, a, b, c, d, in[ 0 ] + 0xd76aa478, 7 );
MD5STEP( F1, d, a, b, c, in[ 1 ] + 0xe8c7b756, 12 );
MD5STEP( F1, c, d, a, b, in[ 2 ] + 0x242070db, 17 );
MD5STEP( F1, b, c, d, a, in[ 3 ] + 0xc1bdceee, 22 );
MD5STEP( F1, a, b, c, d, in[ 4 ] + 0xf57c0faf, 7 );
MD5STEP( F1, d, a, b, c, in[ 5 ] + 0x4787c62a, 12 );
MD5STEP( F1, c, d, a, b, in[ 6 ] + 0xa8304613, 17 );
MD5STEP( F1, b, c, d, a, in[ 7 ] + 0xfd469501, 22 );
MD5STEP( F1, a, b, c, d, in[ 8 ] + 0x698098d8, 7 );
MD5STEP( F1, d, a, b, c, in[ 9 ] + 0x8b44f7af, 12 );
MD5STEP( F1, c, d, a, b, in[ 10 ] + 0xffff5bb1, 17 );
MD5STEP( F1, b, c, d, a, in[ 11 ] + 0x895cd7be, 22 );
MD5STEP( F1, a, b, c, d, in[ 12 ] + 0x6b901122, 7 );
MD5STEP( F1, d, a, b, c, in[ 13 ] + 0xfd987193, 12 );
MD5STEP( F1, c, d, a, b, in[ 14 ] + 0xa679438e, 17 );
MD5STEP( F1, b, c, d, a, in[ 15 ] + 0x49b40821, 22 );
MD5STEP( F2, a, b, c, d, in[ 1 ] + 0xf61e2562, 5 );
MD5STEP( F2, d, a, b, c, in[ 6 ] + 0xc040b340, 9 );
MD5STEP( F2, c, d, a, b, in[ 11 ] + 0x265e5a51, 14 );
MD5STEP( F2, b, c, d, a, in[ 0 ] + 0xe9b6c7aa, 20 );
MD5STEP( F2, a, b, c, d, in[ 5 ] + 0xd62f105d, 5 );
MD5STEP( F2, d, a, b, c, in[ 10 ] + 0x02441453, 9 );
MD5STEP( F2, c, d, a, b, in[ 15 ] + 0xd8a1e681, 14 );
MD5STEP( F2, b, c, d, a, in[ 4 ] + 0xe7d3fbc8, 20 );
MD5STEP( F2, a, b, c, d, in[ 9 ] + 0x21e1cde6, 5 );
MD5STEP( F2, d, a, b, c, in[ 14 ] + 0xc33707d6, 9 );
MD5STEP( F2, c, d, a, b, in[ 3 ] + 0xf4d50d87, 14 );
MD5STEP( F2, b, c, d, a, in[ 8 ] + 0x455a14ed, 20 );
MD5STEP( F2, a, b, c, d, in[ 13 ] + 0xa9e3e905, 5 );
MD5STEP( F2, d, a, b, c, in[ 2 ] + 0xfcefa3f8, 9 );
MD5STEP( F2, c, d, a, b, in[ 7 ] + 0x676f02d9, 14 );
MD5STEP( F2, b, c, d, a, in[ 12 ] + 0x8d2a4c8a, 20 );
MD5STEP( F3, a, b, c, d, in[ 5 ] + 0xfffa3942, 4 );
MD5STEP( F3, d, a, b, c, in[ 8 ] + 0x8771f681, 11 );
MD5STEP( F3, c, d, a, b, in[ 11 ] + 0x6d9d6122, 16 );
MD5STEP( F3, b, c, d, a, in[ 14 ] + 0xfde5380c, 23 );
MD5STEP( F3, a, b, c, d, in[ 1 ] + 0xa4beea44, 4 );
MD5STEP( F3, d, a, b, c, in[ 4 ] + 0x4bdecfa9, 11 );
MD5STEP( F3, c, d, a, b, in[ 7 ] + 0xf6bb4b60, 16 );
MD5STEP( F3, b, c, d, a, in[ 10 ] + 0xbebfbc70, 23 );
MD5STEP( F3, a, b, c, d, in[ 13 ] + 0x289b7ec6, 4 );
MD5STEP( F3, d, a, b, c, in[ 0 ] + 0xeaa127fa, 11 );
MD5STEP( F3, c, d, a, b, in[ 3 ] + 0xd4ef3085, 16 );
MD5STEP( F3, b, c, d, a, in[ 6 ] + 0x04881d05, 23 );
MD5STEP( F3, a, b, c, d, in[ 9 ] + 0xd9d4d039, 4 );
MD5STEP( F3, d, a, b, c, in[ 12 ] + 0xe6db99e5, 11 );
MD5STEP( F3, c, d, a, b, in[ 15 ] + 0x1fa27cf8, 16 );
MD5STEP( F3, b, c, d, a, in[ 2 ] + 0xc4ac5665, 23 );
MD5STEP( F4, a, b, c, d, in[ 0 ] + 0xf4292244, 6 );
MD5STEP( F4, d, a, b, c, in[ 7 ] + 0x432aff97, 10 );
MD5STEP( F4, c, d, a, b, in[ 14 ] + 0xab9423a7, 15 );
MD5STEP( F4, b, c, d, a, in[ 5 ] + 0xfc93a039, 21 );
MD5STEP( F4, a, b, c, d, in[ 12 ] + 0x655b59c3, 6 );
MD5STEP( F4, d, a, b, c, in[ 3 ] + 0x8f0ccc92, 10 );
MD5STEP( F4, c, d, a, b, in[ 10 ] + 0xffeff47d, 15 );
MD5STEP( F4, b, c, d, a, in[ 1 ] + 0x85845dd1, 21 );
MD5STEP( F4, a, b, c, d, in[ 8 ] + 0x6fa87e4f, 6 );
MD5STEP( F4, d, a, b, c, in[ 15 ] + 0xfe2ce6e0, 10 );
MD5STEP( F4, c, d, a, b, in[ 6 ] + 0xa3014314, 15 );
MD5STEP( F4, b, c, d, a, in[ 13 ] + 0x4e0811a1, 21 );
MD5STEP( F4, a, b, c, d, in[ 4 ] + 0xf7537e82, 6 );
MD5STEP( F4, d, a, b, c, in[ 11 ] + 0xbd3af235, 10 );
MD5STEP( F4, c, d, a, b, in[ 2 ] + 0x2ad7d2bb, 15 );
MD5STEP( F4, b, c, d, a, in[ 9 ] + 0xeb86d391, 21 );
m_State[ 0 ] += a;
m_State[ 1 ] += b;
m_State[ 2 ] += c;
m_State[ 3 ] += d;
}
// -------------------------------------------------------------------------------- //
wxString guMD5::MD5( const unsigned char * Data, unsigned int Len )
{
unsigned char MD5Hash[ 16 ];
m_Context.Init();
m_Context.Update( Data, Len );
m_Context.Final( MD5Hash );
wxString RetVal = wxEmptyString;
for( int i = 0; i < 16; i++ )
RetVal += wxString::Format( wxT( "%02x" ), MD5Hash[ i ] );
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString guMD5::MD5File( const wxString &FileName )
{
unsigned char MD5Hash[ 16 ];
#define ChunkSize 1024
m_Context.Init();
wxString RetVal = wxEmptyString;
if( wxFileExists( FileName ) )
{
wxFileInputStream * InStream = new wxFileInputStream( FileName );
size_t FileSize = InStream->GetSize();
unsigned char * m_Buffer = new unsigned char[ ChunkSize ];
size_t BytesRead = 0;
while( BytesRead < FileSize )
{
size_t BytesLeft = FileSize - BytesRead;
size_t Cnt = wxMin( ChunkSize, BytesLeft );
InStream->Read( m_Buffer, Cnt );
BytesRead += Cnt;
m_Context.Update( m_Buffer, Cnt );
}
delete [] m_Buffer;
delete InStream;
}
m_Context.Final( MD5Hash );
for( int i = 0; i < 16; i++ )
RetVal += wxString::Format( wxT( "%02x" ), MD5Hash[ i ] );
return RetVal;
}
// -------------------------------------------------------------------------------- //
//#define MD5TESTING
#ifdef MD5TESTING
int main( void )
{
guMD5 MD5;
printf( MD5.MD5( wxT( "The quick brown fox jumps over the lazy dog" ) ).char_str(), true ); printf( "\n" );
printf( "9e107d9d372bb6826bd81d3542a419d6 <<\n" );
printf( MD5.MD5( wxT( "The quick brown fox jumps over the lazy eog" ) ).char_str(), true ); printf( "\n" );
printf( "ffd93f16876049265fbaef4da268dd0e <<\n" );
}
#endif
// -------------------------------------------------------------------------------- //
| 11,173
|
C++
|
.cpp
| 278
| 35.359712
| 111
| 0.478225
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,576
|
Utils.cpp
|
anonbeat_guayadeque/src/misc/Utils.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Utils.h"
#include "Config.h"
#include "DbLibrary.h"
#include "FileRenamer.h" // NormalizeField
#include "Http.h"
#include "MediaViewer.h"
#include "Settings.h"
#include <wx/process.h>
#include <wx/regex.h>
#include <wx/sstream.h>
#include <wx/uri.h>
#include <wx/protocol/http.h>
#include <wx/zstream.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
bool IsColorDark( const wxColour &color )
{
double darkness = 1 - ( 0.299 * color.Red() + 0.587 * color.Green() + 0.114 * color.Blue() ) / 255;
return darkness >= 0.5;
}
// -------------------------------------------------------------------------------- //
wxString LenToString( wxUint64 len )
{
wxString LenStr;
len /= 1000;
unsigned int w = 0;
unsigned int d = 0;
unsigned int h = 0;
unsigned int m = 0;
if( len >= ( 7 * 24 * 60 * 60 ) )
{
w = len / ( 7 * 24 * 60 * 60 );
len %= ( 7 * 24 * 60 * 60 );
}
if( len >= ( 24 * 60 * 60 ) )
{
d = len / ( 24 * 60 * 60 );
len %= ( 24 * 60 * 60 );
}
if( len >= ( 60 * 60 ) )
{
h = len / ( 60 * 60 );
len %= ( 60 * 60 );
}
if( len >= 60 )
{
m = len / 60;
len %= 60;
}
if( w > 0 )
{
LenStr += LenStr.Format( wxT( "%uw " ), w );
}
if( d > 0 )
{
LenStr += LenStr.Format( wxT( "%ud " ), d );
}
if( h > 0 )
{
LenStr += LenStr.Format( wxT( "%02u:" ), h );
}
LenStr += LenStr.Format( wxT( "%02u:%02llu" ), m, len );
//guLogMessage( wxT( "%lu -> %s" ), len, LenStr.c_str() );
return LenStr;
}
// -------------------------------------------------------------------------------- //
wxString SizeToString( wxFileOffset size )
{
double s = size;
wxString Formats[] = { wxT( "%.0f Bytes" ),
wxT( "%.2f KB" ),
wxT( "%.2f MB" ),
wxT( "%.2f GB" ),
wxT( "%.2f TB" ),
wxT( "%.2f PB" ),
wxT( "%.2f EB" ),
wxT( "%.2f ZB" ),
wxT( "%.2f YB" ) };
int i = 0;
while( i < 9 && s >= 1024 )
{
s = ( 100 * s / 1024 ) / 100.0;
i++;
}
return wxString::Format( Formats[ i ], s );
}
// -------------------------------------------------------------------------------- //
wxArrayString guSplitWords( const wxString &InputStr )
{
wxArrayString RetVal;
wxString TempStr = InputStr;
wxString ResStr;
size_t index, len;
wxRegEx RegEx( wxT( " *([^ ]*|\" *[^\"]* *\") *" ) );
while( TempStr.Length() && RegEx.Matches( TempStr ) )
{
RegEx.GetMatch( &index, &len );
ResStr = RegEx.GetMatch( TempStr, 1 );
ResStr.Replace( wxT( "\"" ), wxT( " " ), true );
RetVal.Add( ResStr.Trim( true ).Trim( false ) );
//guLogMessage( wxT( "%i %s" ), RetVal.Count(), ResStr.Trim( true ).Trim( false ).c_str() );
TempStr = TempStr.Mid( len );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString RemoveSearchFilters( const wxString &SearchStr )
{
wxString RetVal = SearchStr;
wxString TempStr;
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Filters;
if( Config )
{
Filters = Config->ReadAStr( CONFIG_KEY_SEARCH_FILTERS_FILTER, wxEmptyString, CONFIG_PATH_SEARCH_FILTERS );
}
int Count = Filters.Count();
for( int Index = 0; Index < Count; Index++ )
{
TempStr = RetVal.Lower();
int Pos;
while( ( Pos = TempStr.Find( Filters[ Index ] ) ) != wxNOT_FOUND )
{
//RetVal = RetVal.Remove( Pos, Filters[ Index ].Length() );
RetVal = RetVal.Mid( 0, Pos ) + wxT( " " ) + RetVal.Mid( Pos + Filters[ Index ].Length() );
TempStr = RetVal.Lower();
}
}
// Get the Info from the album...
RetVal.Trim( true );
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool SearchCoverWords( const wxString &FileName, const wxArrayString &Strings )
{
int count = Strings.Count();
for( int index = 0; index < count; index++ )
{
if( FileName.Find( Strings[ index ] ) != wxNOT_FOUND )
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
wxImage * guGetRemoteImage( const wxString &url, wxBitmapType &imgtype )
{
wxImage * Image = NULL;
//guLogMessage( wxT( "Downloading '%s'" ), url.c_str() );
wxMemoryOutputStream Buffer;
guHttp Http;
Http.AddHeader( wxT( "User-Agent" ), guDEFAULT_BROWSER_USER_AGENT );
//http.AddHeader( wxT( "Accept: * / *" ) );
//http.SetOpt( CURLOPT_FOLLOWLOCATION, 1 );
try {
if( Http.Get( Buffer, url ) && Buffer.IsOk() && Buffer.GetSize() )
{
long ResCode = Http.GetResCode();
//guLogMessage( wxT( "ResCode: %lu" ), ResCode );
if( ( ResCode < 200 ) || ( ResCode > 299 ) )
{
//guLogMessage( wxT( "Code : %u\n%s" ), ResCode, http.GetResponseHeader().c_str() );
if( ( ResCode == 301 ) || ( ResCode == 302 ) || ( ResCode == 307 ) )
{
wxString Location = Http.GetResHeader();
int Pos = Location.Lower().Find( wxT( "location: " ) );
if( Pos != wxNOT_FOUND )
{
Location = Location.Mid( Pos + 10 );
Location.Truncate( Location.Find( wxT( "\r\n" ) ) );
return guGetRemoteImage( Location, imgtype );
}
}
}
if( ResCode != 200 )
{
guLogMessage( wxT( "Error %lu getting remote image '%s'\n%s" ),
Http.GetResCode(),
url.c_str(),
Http.GetResHeader().c_str() );
}
wxMemoryInputStream Ins( Buffer );
if( Ins.IsOk() )
{
Image = new wxImage( Ins );
if( Image )
{
if( Image->IsOk() )
{
imgtype = Image->GetType();
return Image;
}
delete Image;
}
}
}
else
{
guLogError( wxT( "Could not get the image from '%s'" ), url.c_str() );
}
}
catch( ... )
{
guLogError( wxT( "Exception downloading image '%s'" ), url.c_str() );
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool DownloadImage( const wxString &source, const wxString &target, const wxBitmapType imagetype, int maxwidth, int maxheight )
{
bool RetVal = false;
wxBitmapType ImageType;
wxImage * Image = guGetRemoteImage( source, ImageType );
if( Image )
{
if( maxwidth != -1 )
{
guImageResize( Image, maxwidth, ( maxheight != -1 ) ? maxheight : maxwidth );
}
RetVal = Image->SaveFile( target, imagetype );
delete Image;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool DownloadImage( const wxString &source, const wxString &target, int maxwidth, int maxheight )
{
return DownloadImage( source, target, wxBITMAP_TYPE_JPEG, maxwidth, maxheight );
}
// -------------------------------------------------------------------------------- //
int DownloadFile( const wxString &Source, const wxString &Target )
{
//guLogMessage( wxT( "Downloading %s" ), Source.c_str() );
guHttp http;
http.AddHeader( wxT( "User-Agent" ), guDEFAULT_BROWSER_USER_AGENT );
http.SetOption( CURLOPT_FOLLOWLOCATION, 1L );
http.Get( Target, Source );
long ResCode = http.GetResCode();
if( ( ResCode < 200 ) || ( ResCode > 299 ) )
{
//guLogMessage( wxT( "Code : %u\n%s" ), ResCode, http.GetResponseHeader().c_str() );
if( ( ResCode == 301 ) || ( ResCode == 302 ) || ( ResCode == 307 ) )
{
wxString Location = http.GetResHeader();
int Pos = Location.Lower().Find( wxT( "location: " ) );
if( Pos != wxNOT_FOUND )
{
Location = Location.Mid( Pos + 10 );
Location.Truncate( Location.Find( wxT( "\r\n" ) ) );
return DownloadFile( Location, Target );
}
return 0;
}
}
else
return 1;
return 0;
}
// -------------------------------------------------------------------------------- //
wxString guURLEncode( const wxString &url, bool encodespace )
{
static const wxChar marks[] = wxT( "-_.\"!~*()'" );
wxString RetVal;
wxChar CurChar;
wxCharBuffer CharBuffer = url.ToUTF8();
int Count = strlen( CharBuffer );
for( int Index = 0; Index < Count; ++Index )
{
CurChar = CharBuffer[ Index ];
if( ( CurChar >= 'a' && CurChar <= 'z' ) || ( CurChar >= 'A' && CurChar <= 'Z' ) ||
( CurChar >= '0' && CurChar <= '9' ) || wxStrchr( marks, CurChar ) )
{
RetVal += CurChar;
}
else if( encodespace && ( CurChar == wxT( ' ' ) ) )
{
RetVal += wxT( "+" );
}
else
{
RetVal += wxString::Format( wxT( "%%%02X" ), CurChar & 0xFF );
}
}
//guLogMessage( wxT( "URLEncode: '%s' => '%s'" ), url.c_str(), RetVal.c_str() );
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString guFileDnDEncode( const wxString &file )
{
wxString RetVal;
wxString HexCode;
wxCharBuffer CharBuffer = file.ToUTF8();
size_t StrLen = strlen( CharBuffer );
for( size_t index = 0; index < StrLen; index++ )
{
wxChar C = CharBuffer[ index ];
{
static const wxChar marks[] = wxT( " -_.\"/+!~*()'[]%" ); //~!@#$&*()=:/,;?+'
if( ( C >= 'a' && C <= 'z' ) ||
( C >= 'A' && C <= 'Z' ) ||
( C >= '0' && C <= '9' ) ||
wxStrchr( marks, C ) )
{
RetVal += C;
}
else
{
HexCode.Printf( wxT( "%%%02X" ), C & 0xFF );
RetVal += HexCode;
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guWebExecute( const wxString &Url )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxString BrowserCmd = Config->ReadStr( CONFIG_KEY_GENERAL_BROWSER_COMMAND, wxT( "firefox --new-tab" ), CONFIG_PATH_GENERAL );
wxString Cmd = Url;
Cmd.Replace( wxT( "(" ), wxT( "%28" ) );
Cmd.Replace( wxT( ")" ), wxT( "%29" ) );
//guLogMessage( wxString::Format( wxT( "%s %s" ), BrowserCmd.c_str(), Cmd.c_str() ).c_str() );
//return wxShell( wxString::Format( wxT( "%s \"%s\"" ), BrowserCmd.c_str(), Cmd.c_str() ) );
return wxExecute( BrowserCmd + wxT( " " ) + Cmd );
}
return -1;
}
// -------------------------------------------------------------------------------- //
int guExecute( const wxString &Command )
{
guLogMessage( wxT( "Running command %s" ), Command.c_str() );
return wxExecute( Command );
}
// -------------------------------------------------------------------------------- //
wxFileOffset guGetFileSize( const wxString &FileName )
{
wxStructStat St;
wxStat( FileName, &St );
return St.st_size;
}
// -------------------------------------------------------------------------------- //
wxString GetUrlContent( const wxString &url, const wxString &referer, bool gzipped )
{
guHttp Http;
//char * Buffer;
wxString RetVal = wxEmptyString;
Http.AddHeader( wxT( "User-Agent" ), guDEFAULT_BROWSER_USER_AGENT );
Http.AddHeader( wxT( "Accept" ), wxT( "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" ) );
if( gzipped )
{
Http.AddHeader( wxT( "Accept-Encoding" ), wxT( "gzip, deflate" ) );
}
Http.AddHeader( wxT( "Accept-Charset" ), wxT( "utf-8" ) );
if( !referer.IsEmpty() )
{
Http.AddHeader( wxT( "Referer" ), referer );
}
//guLogMessage( wxT( "Getting content for %s" ), url.c_str() );
wxMemoryOutputStream Buffer;
Http.SetOption( CURLOPT_FOLLOWLOCATION, 1L );
Http.Get( Buffer, url );
if( Buffer.IsOk() )
{
int ResponseCode = Http.GetResCode();
//guLogMessage( wxT( "ResponseCode: %i" ), ResponseCode );
if( ResponseCode >= 300 && ResponseCode < 400 )
{
//guLogMessage( wxT( "Response %u:\n%s\n%s" ), http.GetResponseCode(), http.GetResponseHeader().c_str(), http.GetResponseBody().c_str() );
wxString Location = Http.GetResHeader();
int Pos = Location.Lower().Find( wxT( "location: " ) );
if( Pos != wxNOT_FOUND )
{
Location = Location.Mid( Pos + 10 );
Location.Truncate( Location.Find( wxT( "\r\n" ) ) );
if( Location.StartsWith( wxT( "/" ) ) )
{
wxURI Uri( url );
wxString NewURL;
if( Uri.HasScheme() )
NewURL = Uri.GetScheme() + wxT( "://" );
NewURL += Uri.GetServer();
NewURL += Location;
Location = NewURL;
}
return GetUrlContent( Location, referer, gzipped );
}
}
else if( ResponseCode >= 400 )
return wxEmptyString;
wxString ResponseHeaders = Http.GetResHeader();
//guLogMessage( wxT( "Response %u:\n%s\n%s" ), Http.GetResponseCode(), Http.GetResponseHeader().c_str(), Http.GetResponseBody().c_str() );
if( ResponseHeaders.Lower().Find( wxT( "content-encoding: gzip" ) ) != wxNOT_FOUND )
{
//guLogMessage( wxT( "Response Headers:\n%s" ), ResponseHeaders.c_str() );
wxMemoryInputStream Ins( Buffer );
wxZlibInputStream ZIn( Ins );
wxStringOutputStream Outs( &RetVal );
ZIn.Read( Outs );
}
else
{
//RetVal = wxString( Buffer, wxConvUTF8 );
// wxStringOutputStream Outs( &RetVal );
// wxMemoryInputStream Ins( Buffer );
// Ins.Read( Outs );
if( Buffer.GetLength() )
{
size_t Count = Buffer.GetLength();
const char * pData = ( const char * ) Buffer.GetOutputStreamBuffer()->GetBufferStart();
RetVal = wxString( pData, wxConvUTF8, Count );
if( RetVal.IsEmpty() )
{
RetVal = wxString( pData, wxConvISO8859_1, Count );
if( RetVal.IsEmpty() )
{
RetVal = wxString( pData, wxConvLibc, Count );
}
}
}
}
//free( Buffer );
}
else
{
guLogError( wxT( "Could not get '%s'" ), url.c_str() );
}
//guLogMessage( wxT( "Response:\n%s\n###############" ), RetVal.c_str() );
return RetVal;
}
// -------------------------------------------------------------------------------- //
void CheckSymLinks( wxArrayString &libpaths )
{
char TmpBuf[ 4096 ];
int Result;
int Count = libpaths.Count();
for( int Index = 0; Index < Count; Index++ )
{
Result = readlink( libpaths[ Index ].char_str(), TmpBuf, WXSIZEOF( TmpBuf ) - sizeof( char ) );
if( Result != -1 )
{
TmpBuf[ Result ] = 0;
libpaths[ Index ] = wxString::FromUTF8( TmpBuf );
guLogMessage( wxT( "Detected symbolic link pointing to %s" ), libpaths[ Index ].c_str() );
}
}
}
// -------------------------------------------------------------------------------- //
bool CheckFileLibPath( const wxArrayString &LibPaths, const wxString &filename )
{
int count = LibPaths.Count();
for( int index = 0; index < count; index++ )
{
if( filename.StartsWith( LibPaths[ index ] ) )
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
int guGetFileMode( const wxString &filepath )
{
mode_t mode;
wxStructStat st;
if( !filepath.IsEmpty() && stat( ( const char * ) filepath.fn_str(), &st ) == 0 )
{
mode = st.st_mode;
}
else
{
mode_t mask = umask(0777);
mode = 0666 & ~mask;
umask(mask);
}
return mode;
}
// -------------------------------------------------------------------------------- //
bool guSetFileMode( const wxString &filepath, int mode, bool adding )
{
int m = mode;
if( adding )
{
m |= guGetFileMode( filepath );
}
if( chmod( ( const char * ) filepath.fn_str(), mode ) == -1 )
{
guLogError( wxT( "Failed to set file permission for '%s'"), filepath.c_str() );
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guRenameFile( const wxString &oldname, const wxString &newname, bool overwrite )
{
int Mode = guGetFileMode( oldname );
if( !wxRenameFile( oldname, newname, overwrite ) )
{
return false;
}
return guSetFileMode( newname, Mode );;
}
// -------------------------------------------------------------------------------- //
wxString guGetNextXMLChunk( wxFile &xmlfile, wxFileOffset &CurPos, const char * startstr, const char * endstr, const wxMBConv &conv )
{
#define XMLREAD_BUFFER_SIZE 10240
wxString RetVal;
//wxFileOffset CurPos = xmlfile.Tell();
CurPos = xmlfile.Tell();
wxFileOffset StartPos = wxNOT_FOUND;
wxFileOffset EndPos = wxNOT_FOUND;
int endstrlen = strlen( endstr );
char * Buffer = ( char * ) malloc( XMLREAD_BUFFER_SIZE + 1 );
if( Buffer )
{
while( StartPos == wxNOT_FOUND )
{
int ReadCount = xmlfile.Read( Buffer, XMLREAD_BUFFER_SIZE );
if( ReadCount != wxInvalidOffset && ReadCount > 0 )
{
Buffer[ ReadCount ] = 0;
}
else
{
break;
}
char * StartString = strstr( Buffer, startstr );
if( StartString )
{
StartPos = CurPos + ( StartString - Buffer );
break;
}
else
{
CurPos += ReadCount;
}
}
if( StartPos != wxNOT_FOUND )
{
xmlfile.Seek( StartPos );
CurPos = StartPos;
while( EndPos == wxNOT_FOUND )
{
int ReadCount = xmlfile.Read( Buffer, XMLREAD_BUFFER_SIZE );
if( ReadCount != wxInvalidOffset && ReadCount > 0 )
{
Buffer[ ReadCount ] = 0;
}
else
{
break;
}
char * EndString = strstr( Buffer, endstr );
if( EndString )
{
EndPos = CurPos + ( EndString - Buffer ) + endstrlen;
break;
}
else
{
// Prevent that </artist was partially included
CurPos += ReadCount - endstrlen;
xmlfile.Seek( -endstrlen, wxFromCurrent );
}
}
if( EndPos != wxNOT_FOUND )
{
//guLogMessage( wxT( "Found From %lli => %lli (%lli)" ), StartPos, EndPos, EndPos - StartPos );
int BufferSize = EndPos - StartPos;
if( BufferSize )
{
char * BufferString = ( char * ) malloc( BufferSize + 1 );
if( BufferString )
{
xmlfile.Seek( StartPos );
int ReadCount = xmlfile.Read( BufferString, BufferSize );
if( ReadCount != wxInvalidOffset )
{
BufferString[ ReadCount ] = 0;
RetVal = wxString( BufferString, conv );
//guLogMessage( wxT( "%i %i" ), BufferSize, ReadCount );
}
free( BufferString );
}
}
}
}
free( Buffer );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString guExpandTrackMacros( const wxString &pattern, guTrack * track, const int indexpos )
{
wxString RetVal = pattern;
if( RetVal.Find( guCOPYTO_ARTIST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ARTIST, NormalizeField( track->m_ArtistName ) );
if( RetVal.Find( guCOPYTO_ARTIST_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ARTIST_LOWER, NormalizeField( track->m_ArtistName.Lower() ) );
if( RetVal.Find( guCOPYTO_ARTIST_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ARTIST_UPPER, NormalizeField( track->m_ArtistName.Upper() ) );
if( RetVal.Find( guCOPYTO_ARTIST_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ARTIST_FIRST, NormalizeField( track->m_ArtistName.Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_ALBUMARTIST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUMARTIST, NormalizeField( track->m_AlbumArtist ) );
if( RetVal.Find( guCOPYTO_ALBUMARTIST_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUMARTIST_LOWER, NormalizeField( track->m_AlbumArtist.Lower() ) );
if( RetVal.Find( guCOPYTO_ALBUMARTIST_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUMARTIST_UPPER, NormalizeField( track->m_AlbumArtist.Upper() ) );
if( RetVal.Find( guCOPYTO_ALBUMARTIST_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUMARTIST_FIRST, NormalizeField( track->m_AlbumArtist.Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_ANYARTIST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ANYARTIST, NormalizeField( track->m_AlbumArtist.IsEmpty() ? track->m_ArtistName : track->m_AlbumArtist ) );
if( RetVal.Find( guCOPYTO_ANYARTIST_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ANYARTIST_LOWER, NormalizeField( ( track->m_AlbumArtist.IsEmpty() ? track->m_ArtistName : track->m_AlbumArtist ).Lower() ) );
if( RetVal.Find( guCOPYTO_ANYARTIST_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ANYARTIST_UPPER, NormalizeField( ( track->m_AlbumArtist.IsEmpty() ? track->m_ArtistName : track->m_AlbumArtist ).Upper() ) );
if( RetVal.Find( guCOPYTO_ANYARTIST_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ANYARTIST_FIRST, NormalizeField( ( track->m_AlbumArtist.IsEmpty() ? track->m_ArtistName : track->m_AlbumArtist ).Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_ALBUM ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUM, NormalizeField( track->m_AlbumName ) );
if( RetVal.Find( guCOPYTO_ALBUM_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUM_LOWER, NormalizeField( track->m_AlbumName.Lower() ) );
if( RetVal.Find( guCOPYTO_ALBUM_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUM_UPPER, NormalizeField( track->m_AlbumName.Upper() ) );
if( RetVal.Find( guCOPYTO_ALBUM_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUM_FIRST, NormalizeField( track->m_AlbumName.Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_ALBUM_PATH ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_ALBUM_PATH, NormalizeField( track->m_FileName.BeforeLast( wxT( '/' ) ) ) );
if( RetVal.Find( guCOPYTO_COMPOSER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_COMPOSER, NormalizeField( track->m_Composer ) );
if( RetVal.Find( guCOPYTO_COMPOSER_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_COMPOSER_LOWER, NormalizeField( track->m_Composer.Lower() ) );
if( RetVal.Find( guCOPYTO_COMPOSER_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_COMPOSER_UPPER, NormalizeField( track->m_Composer.Upper() ) );
if( RetVal.Find( guCOPYTO_COMPOSER_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_COMPOSER_FIRST, NormalizeField( track->m_Composer.Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_FILENAME ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_FILENAME, wxFileNameFromPath( track->m_FileName.BeforeLast( wxT( '.' ) ) ) );
if( RetVal.Find( guCOPYTO_GENRE ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_GENRE, NormalizeField( track->m_GenreName ) );
if( RetVal.Find( guCOPYTO_GENRE_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_GENRE_LOWER, NormalizeField( track->m_GenreName.Lower() ) );
if( RetVal.Find( guCOPYTO_GENRE_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_GENRE_UPPER, NormalizeField( track->m_GenreName.Upper() ) );
if( RetVal.Find( guCOPYTO_GENRE_FIRST ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_GENRE_FIRST, NormalizeField( track->m_GenreName.Trim( false )[ 0 ] ) );
if( RetVal.Find( guCOPYTO_NUMBER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_NUMBER, wxString::Format( wxT( "%02u" ), track->m_Number ) );
if( RetVal.Find( guCOPYTO_TITLE ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_TITLE, NormalizeField( track->m_SongName ) );
if( RetVal.Find( guCOPYTO_TITLE_LOWER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_TITLE_LOWER, NormalizeField( track->m_SongName.Lower() ) );
if( RetVal.Find( guCOPYTO_TITLE_UPPER ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_TITLE_UPPER, NormalizeField( track->m_SongName.Upper() ) );
if( RetVal.Find( guCOPYTO_YEAR ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_YEAR, wxString::Format( wxT( "%u" ), track->m_Year ) );
if( RetVal.Find( guCOPYTO_DISC ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_DISC, NormalizeField( track->m_Disk ) );
if( RetVal.Find( guCOPYTO_INDEX ) != wxNOT_FOUND )
RetVal.Replace( guCOPYTO_INDEX, wxString::Format( wxT( "%04u" ), indexpos ) );
return RetVal;
}
// -------------------------------------------------------------------------------- //
bool guIsValidImageFile( const wxString &filename )
{
return filename.EndsWith( wxT( ".jpg" ) ) ||
filename.EndsWith( wxT( ".jpeg" ) ) ||
filename.EndsWith( wxT( ".png" ) ) ||
filename.EndsWith( wxT( ".bmp" ) ) ||
filename.EndsWith( wxT( ".gif" ) );
}
// -------------------------------------------------------------------------------- //
bool guRemoveDir( const wxString &path )
{
wxString CurPath = path;
if( !CurPath.EndsWith( wxT( "/" ) ) )
CurPath += wxT( "/" );
wxDir Dir;
wxString FileName;
Dir.Open( CurPath );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( FileName == wxT( "." ) )
continue;
if( FileName == wxT( ".." ) )
continue;
if( Dir.Exists( CurPath + FileName ) )
{
if( !guRemoveDir( CurPath + FileName ) )
{
guLogMessage( wxT( "Could not remove dir '%s'" ), wxString( CurPath + FileName ).c_str() );
return false;
}
}
else
{
if( !wxRemoveFile( CurPath + FileName ) )
{
guLogMessage( wxT( "Could not remove file '%s'" ), wxString( CurPath + FileName ).c_str() );
return false;
}
}
} while( Dir.GetNext( &FileName ) );
}
return wxRmdir( CurPath );
}
return false;
}
// -------------------------------------------------------------------------------- //
void GetMediaViewerTracks( const guTrackArray &sourcetracks, const wxArrayInt &sourceflags,
const guMediaViewer * mediaviewer, guTrackArray &tracks, wxArrayInt &changedflags )
{
int Count = sourcetracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = sourcetracks[ Index ];
if( Track.m_MediaViewer == mediaviewer )
{
tracks.Add( new guTrack( Track ) );
changedflags.Add( sourceflags[ Index ] );
}
}
}
// -------------------------------------------------------------------------------- //
void GetMediaViewerTracks( const guTrackArray &sourcetracks, const int flags,
const guMediaViewer * mediaviewer, guTrackArray &tracks, wxArrayInt &changedflags )
{
int Count = sourcetracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = sourcetracks[ Index ];
if( Track.m_MediaViewer == mediaviewer )
{
tracks.Add( new guTrack( Track ) );
changedflags.Add( flags );
}
}
}
// -------------------------------------------------------------------------------- //
void GetMediaViewerTracks( const guTrackArray &sourcetracks, const guMediaViewer * mediaviewer, guTrackArray &tracks )
{
int Count = sourcetracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = sourcetracks[ Index ];
if( Track.m_MediaViewer == mediaviewer )
{
tracks.Add( new guTrack( Track ) );
}
}
}
// -------------------------------------------------------------------------------- //
void GetMediaViewersList( const guTrackArray &tracks, wxArrayPtrVoid &MediaViewerPtrs )
{
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = tracks[ Index ];
guMediaViewer * MediaViewer = Track.m_MediaViewer;
if( MediaViewer )
{
if( MediaViewerPtrs.Index( MediaViewer ) == wxNOT_FOUND )
{
MediaViewerPtrs.Add( MediaViewer );
}
}
}
}
// -------------------------------------------------------------------------------- //
wxString ExtractString( const wxString &source, const wxString &start, const wxString &end )
{
int StartPos = source.Find( start );
int EndPos;
if( StartPos != wxNOT_FOUND )
{
wxString SearchStr = source.Mid( StartPos + start.Length() );
EndPos = SearchStr.Find( end );
if( EndPos != wxNOT_FOUND )
{
return SearchStr.Mid( 0, EndPos );
}
}
return wxEmptyString;
}
}
// -------------------------------------------------------------------------------- //
| 32,152
|
C++
|
.cpp
| 810
| 31.37284
| 169
| 0.5004
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,577
|
GIO_Volume.cpp
|
anonbeat_guayadeque/src/misc/GIO_Volume.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "GIO_Volume.h"
#include "EventCommandIds.h"
#include "MainFrame.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
extern "C" {
static void VolumeAdded( GVolumeMonitor * monitor, GVolume * volume, guGIO_VolumeMonitor * volmon )
{
volmon->OnVolumeAdded( volume );
}
static void VolumeRemoved( GVolumeMonitor * monitor, GVolume * volume, guGIO_VolumeMonitor * volmon )
{
volmon->OnVolumeRemoved( volume );
}
static void MountAdded( GVolumeMonitor * monitor, GMount * mount, guGIO_VolumeMonitor * volmon )
{
volmon->OnMountAdded( mount );
}
static void MountRemoved( GVolumeMonitor * monitor, GMount * mount, guGIO_VolumeMonitor * volmon )
{
volmon->OnMountRemoved( mount );
}
static void append_mount( GMount * mount, guGIO_VolumeMonitor * volmon )
{
volmon->OnMountAdded( mount );
}
};
// -------------------------------------------------------------------------------- //
// guGIO_Mount
// -------------------------------------------------------------------------------- //
guGIO_Mount::guGIO_Mount( GMount * mount )
{
m_Mount = mount;
g_object_ref( mount );
char * mount_name = g_mount_get_name( m_Mount );
if( mount_name )
{
m_Name = wxString( mount_name, wxConvUTF8 );
g_free( mount_name );
}
GFile * RootFile = g_mount_get_root( mount );
if( RootFile)
{
char * Path = g_file_get_path( RootFile );
m_MountPath = wxString( Path, wxConvUTF8 ) + wxT( "/" );
// If it is a mtp device find the first writeable folder...
if( m_MountPath.Find( "mtp:" ) != wxNOT_FOUND )
{
wxFileName FileName( m_MountPath );
if( !FileName.IsDirWritable() ) // if cant be created in the default location ...
{
wxString WriteableFolder = FindWriteableFolder( m_MountPath );
if( !WriteableFolder.IsEmpty() )
{
m_MountPath = WriteableFolder;
}
}
}
guLogMessage( wxT( "Mount Path: %s" ), m_MountPath.c_str() );
g_free( Path );
g_object_unref( RootFile );
}
GIcon * Icon = g_mount_get_icon( mount );
if( Icon )
{
char * IconStr = g_icon_to_string( Icon );
if( IconStr )
{
m_IconString = wxString( IconStr, wxConvUTF8 );
guLogMessage( wxT( "IconStr: '%s'" ), m_IconString.c_str() );
g_free( IconStr );
}
g_object_unref( Icon );
}
wxFileConfig Config( wxEmptyString, wxEmptyString, m_MountPath + wxT( ".is_audio_player" ) );
m_Id = Config.Read( wxT( "audio_player_id" ), wxString::Format( wxT( "%08lX" ), wxGetLocalTime() ) );
}
// -------------------------------------------------------------------------------- //
guGIO_Mount::guGIO_Mount( GMount * mount, wxString &mountpath )
{
m_Mount = mount;
g_object_ref( mount );
m_MountPath = mountpath;
if( !m_MountPath.EndsWith( wxT( "/" ) ) )
m_MountPath.Append( wxT( "/" ) );
// If it is a mtp device find the first writeable folder...
if( m_MountPath.Find( "mtp:" ) != wxNOT_FOUND )
{
wxFileName FileName( m_MountPath );
if( !FileName.IsDirWritable() ) // if cant be created in the default location ...
{
wxString WriteableFolder = FindWriteableFolder( m_MountPath );
if( !WriteableFolder.IsEmpty() )
{
m_MountPath = WriteableFolder;
}
}
}
char * mount_name = g_mount_get_name( m_Mount );
if( mount_name )
{
m_Name = wxString( mount_name, wxConvUTF8 );
g_free( mount_name );
}
guLogMessage( wxT( "Mount Path: %s" ), m_MountPath.c_str() );
GIcon * Icon = g_mount_get_icon( mount );
if( Icon )
{
char * IconStr = g_icon_to_string( Icon );
if( IconStr )
{
m_IconString = wxString( IconStr, wxConvUTF8 );
guLogMessage( wxT( "IconStr: '%s'" ), m_IconString.c_str() );
g_free( IconStr );
}
g_object_unref( Icon );
}
wxFileConfig Config( wxEmptyString, wxEmptyString, m_MountPath + wxT( ".is_audio_player" ) );
m_Id = Config.Read( wxT( "audio_player_id" ), wxString::Format( wxT( "%08lX" ), wxGetLocalTime() ) );
}
// -------------------------------------------------------------------------------- //
guGIO_Mount::~guGIO_Mount()
{
}
// -------------------------------------------------------------------------------- //
wxString guGIO_Mount::FindWriteableFolder( const wxString &mountpath )
{
wxDir Dir;
wxString FoundFile;
wxString MountPath = mountpath;
if( !MountPath.EndsWith( wxT( "/" ) ) )
MountPath += wxT( "/" );
Dir.Open( MountPath );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FoundFile, wxEmptyString, wxDIR_DIRS ) )
{
do {
//guLogMessage( wxT( "Found file '%s'" ), FoundFile.c_str() );
if( FoundFile == wxT( "." ) ||
FoundFile == wxT( ".." ) )
continue;
if( wxIsWritable( MountPath + FoundFile + wxT( "/" ) ) )
return MountPath + FoundFile + wxT( "/" );
if( Dir.Exists( MountPath + FoundFile ) )
{
wxString WriteableFolder = FindWriteableFolder( MountPath + FoundFile );
if( !WriteableFolder.IsEmpty() )
{
//guLogMessage( wxT( "Found writeable folder at '%s'" ), WriteableFolder.c_str() );
return WriteableFolder;
}
}
} while( Dir.GetNext( &FoundFile ) );
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guGIO_Mount::CanUnmount( void )
{
return g_mount_can_eject( m_Mount );
}
// -------------------------------------------------------------------------------- //
void Unmounted_Device( GObject * object, GAsyncResult * result, guGIO_Mount * mnt )
{
GError * error = NULL;
if( G_IS_MOUNT( object ) )
{
GMount * mount = ( GMount * ) object;
g_mount_eject_with_operation_finish( mount, result, &error);
}
if( error )
{
if( !g_error_matches( error, G_IO_ERROR, G_IO_ERROR_FAILED_HANDLED ) )
{
guLogError( wxT( "Unable to eject %s" ), error->message );
}
else
{
guLogMessage( wxT( "Eject was already done" ) );
}
g_error_free (error);
}
}
// -------------------------------------------------------------------------------- //
void guGIO_Mount::Unmount( void )
{
g_mount_eject_with_operation( m_Mount, G_MOUNT_UNMOUNT_NONE, NULL, NULL, GAsyncReadyCallback( Unmounted_Device ), this );
}
// -------------------------------------------------------------------------------- //
//
// -------------------------------------------------------------------------------- //
guGIO_VolumeMonitor::guGIO_VolumeMonitor( guMainFrame * mainframe )
{
m_MainFrame = mainframe;
m_MountedVolumes = new guGIO_MountArray();
m_VolumeMonitor = g_volume_monitor_get();
if( m_VolumeMonitor )
{
m_VolumeAddedId = g_signal_connect( m_VolumeMonitor, "volume-added", G_CALLBACK( VolumeAdded ), this );
m_VolumeRemovedId = g_signal_connect( m_VolumeMonitor, "volume-removed", G_CALLBACK( VolumeRemoved ), this );
m_MountAddedId = g_signal_connect( m_VolumeMonitor, "mount-added", G_CALLBACK( MountAdded ), this );
m_MountPreUnmountId = g_signal_connect( m_VolumeMonitor, "mount-pre-unmount", G_CALLBACK( MountRemoved ), this );
m_MountRemovedId = g_signal_connect( m_VolumeMonitor, "mount-removed", G_CALLBACK( MountRemoved ), this );
}
GetCurrentMounts();
}
// -------------------------------------------------------------------------------- //
guGIO_VolumeMonitor::~guGIO_VolumeMonitor( void )
{
guLogMessage( wxT( "Destroying the volume monitor object..." ) );
if( m_VolumeMonitor )
{
g_signal_handler_disconnect( m_VolumeMonitor, m_VolumeAddedId );
g_signal_handler_disconnect( m_VolumeMonitor, m_VolumeRemovedId );
g_signal_handler_disconnect( m_VolumeMonitor, m_MountRemovedId );
g_signal_handler_disconnect( m_VolumeMonitor, m_MountPreUnmountId );
g_signal_handler_disconnect( m_VolumeMonitor, m_MountAddedId );
while( m_MountedVolumes->Count() )
{
delete ( * m_MountedVolumes )[ 0 ];
m_MountedVolumes->RemoveAt( 0 );
}
if( m_MountedVolumes )
{
delete m_MountedVolumes;
}
guLogMessage( wxT( ">> ~guGIO_VolumeMonitor()" ) );
g_object_unref( m_VolumeMonitor );
guLogMessage( wxT( "<< ~guGIO_VolumeMonitor()" ) );
}
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::OnMountAdded( GMount * mount )
{
guLogMessage( wxT( "Mount Added..." ) );
if( FindMount( mount ) == wxNOT_FOUND )
{
if( g_mount_is_shadowed( mount ) )
{
//g_object_unref( mount );
guLogMessage( wxT( "ignored shadowed mount" ) );
return;
}
GVolume * Volume = g_mount_get_volume( mount );
if( !Volume )
{
guLogMessage( wxT( "mount without volume?" ) );
//g_object_unref( mount );
return;
}
g_object_unref( Volume );
GFile * MountRoot = g_mount_get_root( mount );
if( MountRoot )
{
char * mount_path = g_file_get_path( MountRoot );
if( mount_path )
{
wxString MountPath = wxString( mount_path, wxConvUTF8 );
guGIO_Mount * Mount = new guGIO_Mount( mount, MountPath );
if( Mount )
{
m_MountedVolumes->Add( Mount );
wxCommandEvent event( wxEVT_MENU, ID_VOLUMEMANAGER_MOUNT_CHANGED );
event.SetInt( 1 );
wxPostEvent( m_MainFrame, event );
}
g_free( mount_path );
}
g_object_unref( MountRoot );
}
else
{
guLogMessage( wxT( "ignored mount without mount root" ) );
g_object_unref( mount );
return;
}
}
else
{
guLogMessage( wxT( "Mount already added?" ) );
}
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::OnMountRemoved( GMount * mount )
{
guLogMessage( wxT( "Mount Removed..." ) );
int MountIndex;
if( ( MountIndex = FindMount( mount ) ) != wxNOT_FOUND )
{
//guGIO_Mount * Mount = m_MountedVolumes->Item( MountIndex );
m_MountedVolumes->RemoveAt( MountIndex );
wxCommandEvent event( wxEVT_MENU, ID_VOLUMEMANAGER_MOUNT_CHANGED );
event.SetClientData( ( void * ) mount );
event.SetInt( 0 );
wxPostEvent( m_MainFrame, event );
//guLogMessage( wxT( "Posted mount changed event..." ) );
}
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::CheckAudioCDVolume( GVolume * volume, const bool adding )
{
GFile * activation_root = g_volume_get_activation_root( volume );
if( activation_root )
{
char * root_uri = g_file_get_uri( activation_root );
if( root_uri )
{
wxString VolumeUri = wxString::FromUTF8( root_uri );
guLogMessage( wxT( "Uri: %s" ), VolumeUri.c_str() );
if( VolumeUri.StartsWith( "cdda" ) ) // If it is a audio cd
{
wxCommandEvent event( wxEVT_MENU, ID_VOLUMEMANAGER_AUDIOCD_CHANGED );
event.SetInt( adding );
wxPostEvent( m_MainFrame, event );
}
g_free( root_uri );
}
g_object_unref( activation_root );
}
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::OnVolumeAdded( GVolume * volume )
{
guLogMessage( wxT( "Volume Added..." ) );
CheckAudioCDVolume( volume, true );
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::OnVolumeRemoved( GVolume * volume )
{
guLogMessage( wxT( "Volume Removed..." ) );
CheckAudioCDVolume( volume, false );
}
// -------------------------------------------------------------------------------- //
int guGIO_VolumeMonitor::FindMount( GMount * mount )
{
int Count = m_MountedVolumes->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( ( * m_MountedVolumes )[ Index ]->IsMount( mount ) )
return Index;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
wxArrayString guGIO_VolumeMonitor::GetMountNames( void )
{
wxArrayString RetVal;
int Count = m_MountedVolumes->Count();
for( int Index = 0; Index < Count; Index++ )
{
guGIO_Mount * Mount = m_MountedVolumes->Item( Index );
guLogMessage( wxT( "... '%s'" ), Mount->GetName().c_str() );
RetVal.Add( Mount->GetName() );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guGIO_VolumeMonitor::GetCurrentMounts( void )
{
GList * Mounts = g_volume_monitor_get_mounts( m_VolumeMonitor );
if( Mounts )
{
g_list_foreach( Mounts, GFunc( append_mount ), this );
g_list_free( Mounts );
}
}
// -------------------------------------------------------------------------------- //
guGIO_Mount * guGIO_VolumeMonitor::GetMountById( const wxString &id )
{
int Count = m_MountedVolumes->Count();
for( int Index = 0; Index < Count; Index++ )
{
guGIO_Mount * Mount = ( * m_MountedVolumes )[ Index ];
if( Mount->GetId() == id )
return Mount;
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guGIO_Mount * guGIO_VolumeMonitor::GetMountByPath( const wxString &path )
{
int Count = m_MountedVolumes->Count();
for( int Index = 0; Index < Count; Index++ )
{
guGIO_Mount * Mount = ( * m_MountedVolumes )[ Index ];
if( Mount->GetMountPath() == path )
return Mount;
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guGIO_Mount * guGIO_VolumeMonitor::GetMountByName( const wxString &name )
{
int Count = m_MountedVolumes->Count();
for( int Index = 0; Index < Count; Index++ )
{
guGIO_Mount * Mount = ( * m_MountedVolumes )[ Index ];
if( Mount->GetName() == name )
return Mount;
}
return NULL;
}
}
// -------------------------------------------------------------------------------- //
| 16,150
|
C++
|
.cpp
| 428
| 31.17757
| 125
| 0.509259
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,578
|
ArrayStringArray.cpp
|
anonbeat_guayadeque/src/misc/ArrayStringArray.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ArrayStringArray.h"
#include <wx/arrimpl.cpp>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
WX_DEFINE_OBJARRAY( guArrayStringArray )
}
// -------------------------------------------------------------------------------- //
| 1,345
|
C++
|
.cpp
| 28
| 46.892857
| 86
| 0.541508
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,579
|
MainFrame.cpp
|
anonbeat_guayadeque/src/ui/MainFrame.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "MainFrame.h"
#include "Accelerators.h"
#include "AuiDockArt.h"
#include "EventCommandIds.h"
#include "CopyTo.h"
#include "ConfirmExit.h"
#include "EditWithOptions.h"
#include "FileRenamer.h" // NormalizeField
#include "Images.h"
#include "LibUpdate.h"
#include "MediaViewerLibrary.h"
#include "iPodMedia.h"
#include "LocationPanel.h"
#include "Preferences.h"
#include "Settings.h"
#include "TagInfo.h"
#include "TaskBar.h"
#include "TrackChangeInfo.h"
#include "Transcode.h"
#include "Utils.h"
#include "Version.h"
#include <wx/event.h>
#include <wx/statline.h>
#include <wx/notebook.h>
#include <wx/datetime.h>
#include <wx/tokenzr.h>
#include <wx/txtstrm.h>
namespace Guayadeque {
// The default update podcasts timeout is 30 minutes
#define guPODCASTS_UPDATE_TIMEOUT ( 30 * 60 * 1000 )
guMainFrame * guMainFrame::m_MainFrame = NULL;
// -------------------------------------------------------------------------------- //
guMainFrame::guMainFrame( wxWindow * parent, guDbCache * dbcache )
{
SetMainFrame();
//
// Init the Config Object
//
guConfig * Config = ( guConfig * ) guConfig::Get();
if( !Config )
{
guLogError( wxT( "Could not open the guayadeque configuration object" ) );
return;
}
Config->RegisterObject( this );
// Init the Accelerators
guAccelInit();
m_Db = NULL;
m_DbCache = dbcache;
m_DbPodcasts = NULL;
// m_JamendoDb = NULL;
// m_MagnatuneDb = NULL;
m_CopyToThread = NULL;
m_LoadLayoutPending = wxNOT_FOUND;
m_MenuLayoutLoad = NULL;
bool NeedSaveCollections = false;
m_CollectionsMutex.Lock();
if( !Config->LoadCollections( &m_Collections, guMEDIA_COLLECTION_TYPE_NORMAL ) )
{
guMediaCollection * MediaCollection = new guMediaCollection( guMEDIA_COLLECTION_TYPE_NORMAL );
MediaCollection->m_Name = _( "My Music" );
MediaCollection->m_Paths.Add( wxGetHomeDir() + wxT( "/Music" ) );
MediaCollection->m_CoverWords.Add( wxT( "cover" ) );
MediaCollection->m_CoverWords.Add( wxT( "front" ) );
MediaCollection->m_CoverWords.Add( wxT( "folder" ) );
m_Collections.Add( MediaCollection );
NeedSaveCollections = true;
}
if( !Config->LoadCollections( &m_Collections, guMEDIA_COLLECTION_TYPE_JAMENDO ) )
{
guMediaCollection * MediaCollection = new guMediaCollection( guMEDIA_COLLECTION_TYPE_JAMENDO );
MediaCollection->m_Name = wxT( "Jamendo" );
MediaCollection->m_UniqueId = wxT( "Jamendo" );
m_Collections.Add( MediaCollection );
NeedSaveCollections = true;
}
if( !Config->LoadCollections( &m_Collections, guMEDIA_COLLECTION_TYPE_MAGNATUNE ) )
{
guMediaCollection * MediaCollection = new guMediaCollection( guMEDIA_COLLECTION_TYPE_MAGNATUNE );
MediaCollection->m_Name = wxT( "Magnatune" );
MediaCollection->m_UniqueId = wxT( "Magnatune" );
m_Collections.Add( MediaCollection );
NeedSaveCollections = true;
}
Config->LoadCollections( &m_Collections, guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE );
Config->LoadCollections( &m_Collections, guMEDIA_COLLECTION_TYPE_IPOD );
m_CollectionsMutex.Unlock();
if( NeedSaveCollections )
{
Config->SaveCollections( &m_Collections );
}
//
// m_Db->SetLibPath( Config->ReadAStr( wxT( "LibPath" ),
// wxGetHomeDir() + wxT( "/Music" ),
// wxT( "libpaths" ) ) );
// m_LibUpdateThread = NULL;
// m_LibCleanThread = NULL;
m_UpdatePodcastsTimer = NULL;
m_DownloadThread = NULL;
m_NotifySrv = NULL;
m_SelCount = 0;
m_SelLength = 0;
m_SelSize = 0;
//
m_PlayerPanel = NULL;
m_PlayerPlayList = NULL;
m_RadioPanel = NULL;
m_LastFMPanel = NULL;
m_LyricsPanel = NULL;
m_PodcastsPanel = NULL;
m_PlayerVumeters = NULL;
m_FileBrowserPanel = NULL;
m_VolumeMonitor = NULL;
m_LocationPanel = NULL;
m_CoverPanel = NULL;
m_AudioCdPanel = NULL;
m_MenuPlayerPlayList = NULL;
m_MenuPlayerFilters = NULL;
m_MenuPlayerVumeters = NULL;
m_MenuMainLocations = NULL;
m_MenuMainShowCover = NULL;
m_LyricSearchEngine = NULL;
m_LyricSearchContext = NULL;
//
wxImage TaskBarIcon( guImage( guIMAGE_INDEX_guayadeque_taskbar ) );
TaskBarIcon.ConvertAlphaToMask();
m_AppIcon.CopyFromBitmap( TaskBarIcon );
//
m_VolumeMonitor = new guGIO_VolumeMonitor( this );
m_LyricSearchEngine = new guLyricSearchEngine();
//
// guMainFrame GUI components
//
wxPoint MainWindowPos;
MainWindowPos.x = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_POSX, 1, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
MainWindowPos.y = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_POSY, 1, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
wxSize MainWindowSize;
MainWindowSize.x = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_WIDTH, 800, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
MainWindowSize.y = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_HEIGHT, 600, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
Create( parent, wxID_ANY, wxT( "Guayadeque Music Player " ID_GUAYADEQUE_VERSION "-" ID_GUAYADEQUE_REVISION ),
MainWindowPos, MainWindowSize, wxDEFAULT_FRAME_STYLE );
m_AuiManager.SetManagedWindow( this );
m_AuiManager.SetArtProvider( new guAuiDockArt() );
m_AuiManager.SetFlags( wxAUI_MGR_ALLOW_FLOATING |
wxAUI_MGR_TRANSPARENT_DRAG |
wxAUI_MGR_TRANSPARENT_HINT );
wxAuiDockArt * AuiDockArt = m_AuiManager.GetArtProvider();
wxColour BaseColor = guCOLOR_BASE;
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_GRADIENT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_SASH_COLOUR, guCOLOR_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_CAPTION_SIZE, guSIZE_CAPTION );
AuiDockArt->SetMetric( wxAUI_DOCKART_PANE_BORDER_SIZE, guSIZE_BORDER );
AuiDockArt->SetMetric( wxAUI_DOCKART_SASH_SIZE, guSIZE_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_GRADIENT_TYPE, guGRADIENT_TYPE );
if( Config->ReadBool( CONFIG_KEY_GENERAL_LOAD_DEFAULT_LAYOUTS, false, CONFIG_PATH_GENERAL ) )
{
Config->WriteBool( CONFIG_KEY_GENERAL_LOAD_DEFAULT_LAYOUTS, false, CONFIG_PATH_GENERAL );
Config->SetIgnoreLayouts( true );
}
//m_MainNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
m_DestroyLastWindow = false;
m_MainNotebook = new guAuiNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxAUI_NB_DEFAULT_STYLE );
guMediaViewerLibrary * MediaViewer = new guMediaViewerLibrary( m_MainNotebook,
m_Collections[ 0 ],
ID_COLLECTIONS_BASE,
this,
guMEDIAVIEWER_MODE_NONE,
NULL );
MediaViewer->SetDefault( true );
m_MediaViewers.Add( MediaViewer );
m_Db = MediaViewer->GetDb();
m_VisiblePanels = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_VISIBLE_PANELS, guPANEL_MAIN_VISIBLE_DEFAULT, CONFIG_PATH_MAIN_WINDOW );
if( Config->GetIgnoreLayouts() )
m_VisiblePanels = guPANEL_MAIN_VISIBLE_DEFAULT;
//guLogMessage( wxT( "%08X" ), m_VisiblePanels );
m_MainStatusBar = new guStatusBar( this );
SetStatusBar( m_MainStatusBar );
//MainFrameSizer = new wxBoxSizer( wxVERTICAL );
SetStatusText( _( "Welcome to Guayadeque " ) );
SetStatusBarPane( 0 );
//
if( m_VisiblePanels & guPANEL_MAIN_PLAYERVUMETERS )
{
ShowMainPanel( guPANEL_MAIN_PLAYERVUMETERS, true );
}
if( m_VisiblePanels & guPANEL_MAIN_LOCATIONS )
{
ShowMainPanel( guPANEL_MAIN_LOCATIONS, true );
}
m_PlayerFilters = new guPlayerFilters( this, m_Db );
m_AuiManager.AddPane( m_PlayerFilters, wxAuiPaneInfo().Name( wxT( "PlayerFilters" ) ).Caption( _( "Filters" ) ).
DestroyOnClose( false ).Resizable( true ).Floatable( true ).MinSize( 150, 63 ).
CloseButton( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL ) ).
Bottom().Layer( 0 ).Row( 1 ).Position( 0 ) );
m_PlayerPlayList = new guPlayerPlayList( this, m_Db, &m_AuiManager );
m_AuiManager.AddPane( m_PlayerPlayList, wxAuiPaneInfo().Name( wxT( "PlayerPlayList" ) ).
DestroyOnClose( false ).Resizable( true ).Floatable( true ).MinSize( 150, 100 ).
CloseButton( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL ) ).
Bottom().Layer( 0 ).Row( 2 ).Position( 0 ) );
m_PlayerPanel = new guPlayerPanel( this, m_Db, m_PlayerPlayList->GetPlayListCtrl(), m_PlayerFilters );
m_PlayerPlayList->SetPlayerPanel( m_PlayerPanel );
m_PlayerPanel->SetPlayerVumeters( m_PlayerVumeters );
MediaViewer->SetPlayerPanel( m_PlayerPanel );
m_AuiManager.AddPane( m_PlayerPanel, wxAuiPaneInfo().Name( wxT( "PlayerPanel" ) ).
CloseButton( false ).DestroyOnClose( false ).
Resizable( true ).MinSize( 100, 100 ).
CaptionVisible( true ).
Bottom().Layer( 0 ).Row( 0 ).Position( 0 ) );
if( m_VisiblePanels & guPANEL_MAIN_SHOWCOVER )
{
ShowMainPanel( guPANEL_MAIN_SHOWCOVER, true );
}
CreateMenu();
if( m_LocationPanel )
m_LocationPanel->Lock();
m_NBPerspective = Config->ReadStr( CONFIG_KEY_MAIN_WINDOW_NOTEBOOK_LAYOUT, wxEmptyString, CONFIG_PATH_MAIN_WINDOW );
if( !Config->GetIgnoreLayouts() && !m_NBPerspective.IsEmpty() )
{
LoadTabsPerspective( m_NBPerspective );
}
else
{
wxCommandEvent ShowEvent;
ShowEvent.SetInt( 1 );
wxCommandEvent Event( wxEVT_MENU, ID_COLLECTIONS_BASE );
Event.SetInt( 1 );
OnCollectionCommand( Event );
// Radio Page
if( m_VisiblePanels & guPANEL_MAIN_RADIOS )
{
OnViewRadio( ShowEvent );
}
if( m_VisiblePanels & guPANEL_MAIN_AUDIOCD )
{
OnViewAudioCD( ShowEvent );
}
// LastFM Info Panel
if( m_VisiblePanels & guPANEL_MAIN_LASTFM )
{
OnViewLastFM( ShowEvent );
}
// Lyrics Panel
if( m_VisiblePanels & guPANEL_MAIN_LYRICS )
{
OnViewLyrics( ShowEvent );
}
// Podcasts Page
if( m_VisiblePanels & guPANEL_MAIN_PODCASTS )
{
OnViewPodcasts( ShowEvent );
}
// FileSystem Page
if( m_VisiblePanels & guPANEL_MAIN_FILEBROWSER )
{
OnViewFileBrowser( ShowEvent );
}
}
m_AuiManager.AddPane( m_MainNotebook, wxAuiPaneInfo().Name( wxT( "PlayerSelector" ) ).
CaptionVisible( false ).CloseButton( false ).DestroyOnClose( false ).
CenterPane() );
//m_AuiManager.Update();
wxString Perspective = Config->ReadStr( CONFIG_KEY_MAIN_WINDOW_LAST_LAYOUT, wxEmptyString, CONFIG_PATH_MAIN_WINDOW );
if( !Config->GetIgnoreLayouts() && !Perspective.IsEmpty() )
{
//m_AuiManager.LoadPerspective( Perspective, true );
LoadPerspective( Perspective );
}
else
{
Perspective = wxT( "layout2|name=PlayerVumeters;caption=" ) + wxString( _( "VU Meters" ) );
Perspective += wxT( ";state=2098172;dir=4;layer=0;row=1;pos=1;prop=37931;bestw=20;besth=20;minw=20;minh=20;maxw=-1;maxh=-1;floatx=95;floaty=866;floatw=28;floath=44|" );
Perspective += wxT( "name=PlayerFilters;caption=" ) + wxString( _( "Filters" ) );
Perspective += wxT( ";state=2098172;dir=4;layer=0;row=1;pos=3;prop=44139;bestw=138;besth=63;minw=50;minh=50;maxw=-1;maxh=-1;floatx=81;floaty=863;floatw=146;floath=87|" );
Perspective += wxT( "name=PlayerPlayList;caption=" ) + wxString( _( "Now Playing" ) );
Perspective += wxT( ";state=2099196;dir=4;layer=0;row=1;pos=2;prop=195862;bestw=100;besth=100;minw=100;minh=100;maxw=-1;maxh=-1;floatx=81;floaty=534;floatw=300;floath=265|" );
Perspective += wxT( "name=PlayerPanel;caption=;state=1020;dir=4;layer=0;row=1;pos=0;prop=122068;bestw=356;besth=177;minw=100;minh=100;maxw=-1;maxh=-1;floatx=83;floaty=746;floatw=364;floath=201|" );
Perspective += wxT( "name=PlayerSelector;caption=;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=20;besth=20;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
Perspective += wxT( "dock_size(5,0,0)=22|dock_size(4,0,1)=302|" );
m_AuiManager.LoadPerspective( Perspective, true );
//m_AuiManager.Update();
}
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
if( !PaneInfo.IsShown() )
{
m_VisiblePanels = m_VisiblePanels & ( guPANEL_MAIN_PLAYERPLAYLIST |
guPANEL_MAIN_PLAYERFILTERS |
guPANEL_MAIN_PLAYERVUMETERS |
guPANEL_MAIN_LOCATIONS |
guPANEL_MAIN_SHOWCOVER );
// Reset the Menu entry for all elements
// ResetViewMenuState();
}
m_CurrentPage = m_MainNotebook->GetPage( m_MainNotebook->GetSelection() );
if( m_LocationPanel )
m_LocationPanel->Unlock();
//
m_TaskBarIcon = NULL;
m_DBusServer = new guDBusServer( NULL );
guDBusServer::Set( m_DBusServer );
if( !m_DBusServer )
{
guLogError( wxT( "Could not create the dbus server object" ) );
}
// Init the MPRIS object
//m_MPRIS = NULL;
m_MPRIS = new guMPRIS( m_DBusServer, m_PlayerPanel );
if( !m_MPRIS )
{
guLogError( wxT( "Could not create the mpris dbus object" ) );
}
m_MPRIS2 = new guMPRIS2( m_DBusServer, m_PlayerPanel, m_Db );
if( !m_MPRIS2 )
{
guLogError( wxT( "Could not create the mpris2 dbus object" ) );
}
guMPRIS2::Set( m_MPRIS2 );
// Init the MMKeys object
m_MMKeys = new guMMKeys( m_DBusServer, m_PlayerPanel );
if( !m_MMKeys )
{
guLogError( wxT( "Could not create the mmkeys dbus object" ) );
}
m_GSession = new guGSession( m_DBusServer );
if( !m_GSession )
{
guLogError( wxT( "Could not create the gnome session dbus object" ) );
}
m_NotifySrv = new guDBusNotify( m_DBusServer );
if( !m_NotifySrv )
{
guLogMessage( wxT( "Could not create the notify dbus object" ) );
}
m_PlayerPanel->SetNotifySrv( m_NotifySrv );
//m_DBusServer->Run();
// Fill the Format extensions array
guIsValidAudioFile( wxEmptyString );
if( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN, IsFullScreen(), CONFIG_PATH_MAIN_WINDOW ) != IsFullScreen() )
{
ShowFullScreen( !IsFullScreen(), wxFULLSCREEN_NOSTATUSBAR | wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION );
}
// // Load the layouts menu
// CreateLayoutMenus();
// Bind events
Bind( wxEVT_IDLE, &guMainFrame::OnIdle, this );
Bind( wxEVT_SIZE, &guMainFrame::OnSize, this );
Bind( wxEVT_ICONIZE, &guMainFrame::OnIconize, this );
Bind( wxEVT_MENU, &guMainFrame::OnPlayStream, this, ID_MENU_PLAY_STREAM );
Bind( wxEVT_MENU, &guMainFrame::OnUpdatePodcasts, this, ID_MENU_UPDATE_PODCASTS );
Bind( wxEVT_MENU, &guMainFrame::OnCloseTab, this, ID_MENU_VIEW_CLOSEWINDOW );
Bind( wxEVT_MENU, &guMainFrame::OnShowCaptions, this, ID_MENU_HIDE_CAPTIONS );
Bind( wxEVT_MENU, &guMainFrame::OnQuit, this, ID_MENU_QUIT );
Bind( wxEVT_MENU, &guMainFrame::OnChangeVolume, this, ID_MENU_VOLUME_DOWN, ID_MENU_VOLUME_UP );
// Bind( wxEVT_MENU, &guMainFrame::LibraryUpdated, this, ID_LIBRARY_UPDATED );
// Bind( wxEVT_MENU, &guMainFrame::OnJamendoUpdated, this, ID_JAMENDO_UPDATE_FINISHED );
// Bind( wxEVT_MENU, &guMainFrame::OnMagnatuneUpdated, this, ID_MAGNATUNE_UPDATE_FINISHED );
// Bind( wxEVT_MENU, &guMainFrame::DoLibraryClean, this, ID_LIBRARY_DOCLEANDB );
// Bind( wxEVT_MENU, &guMainFrame::LibraryCleanFinished, this, ID_LIBRARY_CLEANFINISHED );
// Bind( wxEVT_MENU, &guMainFrame::LibraryReloadControls, this, ID_LIBRARY_RELOADCONTROLS );
Bind( wxEVT_MENU, &guMainFrame::OnAudioScrobbleUpdate, this, ID_AUDIOSCROBBLE_UPDATED );
Bind( wxEVT_CLOSE_WINDOW, &guMainFrame::OnCloseWindow, this );
//Bind( wxEVT_ICONIZE, &guMainFrame::OnIconizeWindow, this );
Bind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES );
Bind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_COMMANDS );
Bind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_COPYTO );
Bind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_LINKS );
Bind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_COLLECTION_NEW );
Bind( wxEVT_MENU, &guMainFrame::OnUpdateTrack, this, ID_PLAYERPANEL_TRACKCHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerStatusChanged, this, ID_PLAYERPANEL_STATUSCHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerTrackListChanged, this, ID_PLAYERPANEL_TRACKLISTCHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerCapsChanged, this, ID_PLAYERPANEL_CAPSCHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerVolumeChanged, this, ID_PLAYERPANEL_VOLUMECHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerSeeked, this, ID_PLAYERPANEL_SEEKED );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_TRACK );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ALBUM );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ALBUMARTIST );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_COMPOSER );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ARTIST );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_YEAR );
Bind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_GENRE );
Bind( wxEVT_MENU, &guMainFrame::OnSelectLocation, this, ID_MAINFRAME_SELECT_LOCATION );
Bind( wxEVT_MENU, &guMainFrame::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_ALLOW_PLAYLIST );
Bind( wxEVT_MENU, &guMainFrame::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_DENY_PLAYLIST );
Bind( wxEVT_MENU, &guMainFrame::OnPlay, this, ID_PLAYERPANEL_PLAY );
Bind( wxEVT_MENU, &guMainFrame::OnStop, this, ID_PLAYERPANEL_STOP );
Bind( wxEVT_MENU, &guMainFrame::OnStopAtEnd, this, ID_PLAYER_PLAYLIST_STOP_ATEND );
Bind( wxEVT_MENU, &guMainFrame::OnClearPlaylist, this, ID_PLAYER_PLAYLIST_CLEAR );
Bind( wxEVT_MENU, &guMainFrame::OnNextTrack, this, ID_PLAYERPANEL_NEXTTRACK );
Bind( wxEVT_MENU, &guMainFrame::OnPrevTrack, this, ID_PLAYERPANEL_PREVTRACK );
Bind( wxEVT_MENU, &guMainFrame::OnNextAlbum, this, ID_PLAYERPANEL_NEXTALBUM );
Bind( wxEVT_MENU, &guMainFrame::OnPrevAlbum, this, ID_PLAYERPANEL_PREVALBUM );
Bind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_SMART );
Bind( wxEVT_MENU, &guMainFrame::OnRandomize, this, ID_PLAYER_PLAYLIST_RANDOMPLAY );
Bind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST );
Bind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_REPEAT_TRACK );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerPlayListUpdateTitle, this, ID_PLAYER_PLAYLIST_UPDATETITLE );
Bind( wxEVT_MENU, &guMainFrame::OnAbout, this, ID_MENU_ABOUT );
Bind( wxEVT_MENU, &guMainFrame::OnHelp, this, ID_MENU_HELP );
Bind( wxEVT_MENU, &guMainFrame::OnCommunity, this, ID_MENU_COMMUNITY );
Bind( wxEVT_MENU, &guMainFrame::OnCopyTracksTo, this, ID_MAINFRAME_COPYTO );
Bind( wxEVT_MENU, &guMainFrame::OnCopyTracksToDevice, this, ID_MAINFRAME_COPYTODEVICE_TRACKS );
Bind( wxEVT_MENU, &guMainFrame::OnCopyPlayListToDevice, this, ID_MAINFRAME_COPYTODEVICE_PLAYLIST );
// Bind( wxEVT_MENU, &guMainFrame::OnUpdateLabels, this, ID_LABEL_UPDATELABELS );
Bind( wxEVT_MENU, &guMainFrame::OnCreateNewLayout, this, ID_MENU_LAYOUT_CREATE );
Bind( wxEVT_MENU, &guMainFrame::OnLoadLayout, this, ID_MENU_LAYOUT_LOAD, ID_MENU_LAYOUT_LOAD + 99 );
Bind( wxEVT_MENU, &guMainFrame::OnDeleteLayout, this, ID_MENU_LAYOUT_DELETE, ID_MENU_LAYOUT_DELETE + 99 );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_PLAYLIST );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_FILTERS );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_VUMETERS );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_NOTEBOOK );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_MAIN_LOCATIONS );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_MAIN_SHOWCOVER );
Bind( wxEVT_MENU, &guMainFrame::OnViewRadio, this, ID_MENU_VIEW_RADIO );
Bind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_TEXTSEARCH );
Bind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_LABELS );
Bind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_GENRES );
Bind( wxEVT_MENU, &guMainFrame::OnRadioProperties, this, ID_MENU_VIEW_RAD_PROPERTIES );
Bind( wxEVT_MENU, &guMainFrame::OnViewLastFM, this, ID_MENU_VIEW_LASTFM );
Bind( wxEVT_MENU, &guMainFrame::OnViewLyrics, this, ID_MENU_VIEW_LYRICS );
Bind( wxEVT_MENU, &guMainFrame::OnViewAudioCD, this, ID_MENU_VIEW_AUDIOCD );
Bind( wxEVT_MENU, &guMainFrame::OnViewPodcasts, this, ID_MENU_VIEW_PODCASTS );
Bind( wxEVT_MENU, &guMainFrame::OnPodcastsShowPanel, this, ID_MENU_VIEW_POD_CHANNELS );
Bind( wxEVT_MENU, &guMainFrame::OnPodcastsShowPanel, this, ID_MENU_VIEW_POD_DETAILS );
Bind( wxEVT_MENU, &guMainFrame::OnPodcastsProperties, this, ID_MENU_VIEW_POD_PROPERTIES );
Bind( wxEVT_MENU, &guMainFrame::OnViewFileBrowser, this, ID_MENU_VIEW_FILEBROWSER );
Bind( wxEVT_MENU, &guMainFrame::OnLibraryCoverChanged, this, ID_ALBUM_COVER_CHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnPlayerPanelCoverChanged, this, ID_PLAYERPANEL_COVERUPDATED );
Bind( wxEVT_MENU, &guMainFrame::OnViewFullScreen, this, ID_MENU_VIEW_FULLSCREEN );
Bind( wxEVT_MENU, &guMainFrame::OnViewStatusBar, this, ID_MENU_VIEW_STATUSBAR );
Bind( wxEVT_MENU, &guMainFrame::OnMountMonitorUpdated, this, ID_VOLUMEMANAGER_MOUNT_CHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnAudioCdVolumeUpdated, this, ID_VOLUMEMANAGER_AUDIOCD_CHANGED );
Bind( wxEVT_MENU, &guMainFrame::OnGaugeCreate, this, ID_STATUSBAR_GAUGE_CREATE );
Bind( wxEVT_MENU, &guMainFrame::OnGaugePulse, this, ID_STATUSBAR_GAUGE_PULSE );
Bind( wxEVT_MENU, &guMainFrame::OnGaugeSetMax, this, ID_STATUSBAR_GAUGE_SETMAX );
Bind( wxEVT_MENU, &guMainFrame::OnGaugeUpdate, this, ID_STATUSBAR_GAUGE_UPDATE );
Bind( wxEVT_MENU, &guMainFrame::OnGaugeRemove, this, ID_STATUSBAR_GAUGE_REMOVE );
Bind( wxEVT_MENU, &guMainFrame::OnPlayListUpdated, this, ID_PLAYLIST_UPDATED );
Bind( guPodcastEvent, &guMainFrame::OnPodcastItemUpdated, this, ID_PODCASTS_ITEM_UPDATED );
Bind( wxEVT_MENU, &guMainFrame::OnRemovePodcastThread, this, ID_MAINFRAME_REMOVEPODCASTTHREAD );
Bind( wxEVT_MENU, &guMainFrame::OnSetForceGapless, this, ID_MAINFRAME_SETFORCEGAPLESS );
Bind( wxEVT_MENU, &guMainFrame::OnSetAudioScrobble, this, ID_MAINFRAME_SETAUDIOSCROBBLE );
m_AuiManager.Bind( wxEVT_AUI_PANE_CLOSE, &guMainFrame::OnMainPaneClose, this );
m_MainNotebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CHANGED, &guMainFrame::OnPageChanged, this );
m_MainNotebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &guMainFrame::OnPageClosed, this );
Bind( wxEVT_MENU, &guMainFrame::OnUpdateSelInfo, this, ID_MAINFRAME_UPDATE_SELINFO );
Bind( wxEVT_MENU, &guMainFrame::OnRequestCurrentTrack, this, ID_MAINFRAME_REQUEST_CURRENTTRACK );
Bind( wxEVT_MENU, &guMainFrame::OnLyricFound, this, ID_LYRICS_LYRICFOUND );
Bind( wxEVT_MENU, &guMainFrame::OnLyricSearchFirst, this, ID_MAINFRAME_LYRICSSEARCHFIRST );
Bind( wxEVT_MENU, &guMainFrame::OnLyricSearchNext, this, ID_MAINFRAME_LYRICSSEARCHNEXT );
Bind( wxEVT_MENU, &guMainFrame::OnLyricSaveChanges, this, ID_MAINFRAME_LYRICSSAVECHANGES );
Bind( wxEVT_MENU, &guMainFrame::OnLyricExecCommand, this, ID_MAINFRAME_LYRICSEXECCOMMAND );
Bind( guConfigUpdatedEvent, &guMainFrame::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guMainFrame::OnSongSetRating, this, ID_PLAYERPANEL_SETRATING_0, ID_PLAYERPANEL_SETRATING_5 );
Bind( wxEVT_MENU, &guMainFrame::OnRaiseWindow, this, ID_MAINFRAME_WINDOW_RAISE );
Bind( wxEVT_MENU, &guMainFrame::OnLoadPlayList, this, ID_MAINFRAME_LOAD_PLAYLIST );
Bind( wxEVT_MENU, &guMainFrame::OnViewPortableDevice, this, ID_MENU_VIEW_PORTABLE_DEVICE, ID_MENU_VIEW_PORTABLE_DEVICE + 99 );
Bind( wxEVT_MENU, &guMainFrame::OnCollectionCommand, this, ID_COLLECTIONS_BASE, ID_COLLECTIONS_BASE + ( guCOLLECTION_ACTION_COUNT * guCOLLECTIONS_MAXCOUNT ) );
Bind( wxEVT_MENU, &guMainFrame::OnUpdateRadio, this, ID_RADIO_DOUPDATE );
Bind( wxEVT_MENU, &guMainFrame::OnMediaViewerClosed, this, ID_MAINFRAME_MEDIAVIEWER_CLOSED );
}
// -------------------------------------------------------------------------------- //
guMainFrame::~guMainFrame()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxPoint MainWindowPos = GetPosition();
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_POSX, MainWindowPos.x, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_POSY, MainWindowPos.y, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
wxSize MainWindowSize = GetSize();
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_WIDTH, MainWindowSize.x, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_POSITIONS_HEIGHT, MainWindowSize.y, CONFIG_PATH_MAIN_WINDOW_POSITIONS );
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_VISIBLE_PANELS, m_VisiblePanels, CONFIG_PATH_MAIN_WINDOW );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( wxT( "PlayerPlayList" ) );
PaneInfo.Caption( _( "Now Playing" ) );
Config->WriteStr( CONFIG_KEY_MAIN_WINDOW_LAST_LAYOUT, m_AuiManager.SavePerspective(), CONFIG_PATH_MAIN_WINDOW );
Config->WriteStr( CONFIG_KEY_MAIN_WINDOW_NOTEBOOK_LAYOUT, m_MainNotebook->SavePerspective(), CONFIG_PATH_MAIN_WINDOW );
Config->WriteBool( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN, IsFullScreen() , CONFIG_PATH_MAIN_WINDOW );
Config->WriteBool( CONFIG_KEY_MAIN_WINDOW_STATUS_BAR, m_MainStatusBar->IsShown() , CONFIG_PATH_MAIN_WINDOW );
}
if( m_TaskBarIcon )
delete m_TaskBarIcon;
// destroy the mpris object
if( m_MPRIS )
{
delete m_MPRIS;
}
if( m_MPRIS2 )
{
delete m_MPRIS2;
}
if( m_GSession )
{
delete m_GSession;
}
if( m_MMKeys )
{
delete m_MMKeys;
}
if( m_NotifySrv )
{
m_PlayerPanel->SetNotifySrv( NULL );
delete m_NotifySrv;
}
if( m_DBusServer )
{
delete m_DBusServer;
}
if( m_VolumeMonitor )
{
delete m_VolumeMonitor;
}
m_AuiManager.UnInit();
if( m_CopyToThread )
{
m_CopyToThreadMutex.Lock();
m_CopyToThread->Pause();
m_CopyToThread->Delete();
m_CopyToThread = NULL;
m_CopyToThreadMutex.Unlock();
}
if( m_LyricSearchContext )
{
delete m_LyricSearchContext;
}
if( m_LyricSearchEngine )
{
delete m_LyricSearchEngine;
}
// Unbind events
Unbind( wxEVT_IDLE, &guMainFrame::OnIdle, this );
Unbind( wxEVT_SIZE, &guMainFrame::OnSize, this );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayStream, this, ID_MENU_PLAY_STREAM );
Unbind( wxEVT_MENU, &guMainFrame::OnUpdatePodcasts, this, ID_MENU_UPDATE_PODCASTS );
Unbind( wxEVT_MENU, &guMainFrame::OnCloseTab, this, ID_MENU_VIEW_CLOSEWINDOW );
Unbind( wxEVT_MENU, &guMainFrame::OnShowCaptions, this, ID_MENU_HIDE_CAPTIONS );
Unbind( wxEVT_MENU, &guMainFrame::OnQuit, this, ID_MENU_QUIT );
Unbind( wxEVT_MENU, &guMainFrame::OnChangeVolume, this, ID_MENU_VOLUME_DOWN, ID_MENU_VOLUME_UP );
// Unbind( wxEVT_MENU, &guMainFrame::LibraryUpdated, this, ID_LIBRARY_UPDATED );
// Unbind( wxEVT_MENU, &guMainFrame::OnJamendoUpdated, this, ID_JAMENDO_UPDATE_FINISHED );
// Unbind( wxEVT_MENU, &guMainFrame::OnMagnatuneUpdated, this, ID_MAGNATUNE_UPDATE_FINISHED );
// Unbind( wxEVT_MENU, &guMainFrame::DoLibraryClean, this, ID_LIBRARY_DOCLEANDB );
// Unbind( wxEVT_MENU, &guMainFrame::LibraryCleanFinished, this, ID_LIBRARY_CLEANFINISHED );
// Unbind( wxEVT_MENU, &guMainFrame::LibraryReloadControls, this, ID_LIBRARY_RELOADCONTROLS );
Unbind( wxEVT_MENU, &guMainFrame::OnAudioScrobbleUpdate, this, ID_AUDIOSCROBBLE_UPDATED );
Unbind( wxEVT_CLOSE_WINDOW, &guMainFrame::OnCloseWindow, this );
//Unbind( wxEVT_ICONIZE, &guMainFrame::OnIconizeWindow, this );
Unbind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES );
Unbind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_COMMANDS );
Unbind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_COPYTO );
Unbind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_PREFERENCES_LINKS );
Unbind( wxEVT_MENU, &guMainFrame::OnPreferences, this, ID_MENU_COLLECTION_NEW );
Unbind( wxEVT_MENU, &guMainFrame::OnUpdateTrack, this, ID_PLAYERPANEL_TRACKCHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerStatusChanged, this, ID_PLAYERPANEL_STATUSCHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerTrackListChanged, this, ID_PLAYERPANEL_TRACKLISTCHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerCapsChanged, this, ID_PLAYERPANEL_CAPSCHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerVolumeChanged, this, ID_PLAYERPANEL_VOLUMECHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerSeeked, this, ID_PLAYERPANEL_SEEKED );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_TRACK );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ALBUM );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ALBUMARTIST );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_COMPOSER );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_ARTIST );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_YEAR );
Unbind( wxEVT_MENU, &guMainFrame::OnSetSelection, this, ID_MAINFRAME_SELECT_GENRE );
Unbind( wxEVT_MENU, &guMainFrame::OnSelectLocation, this, ID_MAINFRAME_SELECT_LOCATION );
Unbind( wxEVT_MENU, &guMainFrame::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_ALLOW_PLAYLIST );
Unbind( wxEVT_MENU, &guMainFrame::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_DENY_PLAYLIST );
Unbind( wxEVT_MENU, &guMainFrame::OnPlay, this, ID_PLAYERPANEL_PLAY );
Unbind( wxEVT_MENU, &guMainFrame::OnStop, this, ID_PLAYERPANEL_STOP );
Unbind( wxEVT_MENU, &guMainFrame::OnStopAtEnd, this, ID_PLAYER_PLAYLIST_STOP_ATEND );
Unbind( wxEVT_MENU, &guMainFrame::OnClearPlaylist, this, ID_PLAYER_PLAYLIST_CLEAR );
Unbind( wxEVT_MENU, &guMainFrame::OnNextTrack, this, ID_PLAYERPANEL_NEXTTRACK );
Unbind( wxEVT_MENU, &guMainFrame::OnPrevTrack, this, ID_PLAYERPANEL_PREVTRACK );
Unbind( wxEVT_MENU, &guMainFrame::OnNextAlbum, this, ID_PLAYERPANEL_NEXTALBUM );
Unbind( wxEVT_MENU, &guMainFrame::OnPrevAlbum, this, ID_PLAYERPANEL_PREVALBUM );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_SMART );
Unbind( wxEVT_MENU, &guMainFrame::OnRandomize, this, ID_PLAYER_PLAYLIST_RANDOMPLAY );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayMode, this, ID_PLAYER_PLAYMODE_REPEAT_TRACK );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerPlayListUpdateTitle, this, ID_PLAYER_PLAYLIST_UPDATETITLE );
Unbind( wxEVT_MENU, &guMainFrame::OnAbout, this, ID_MENU_ABOUT );
Unbind( wxEVT_MENU, &guMainFrame::OnHelp, this, ID_MENU_HELP );
Unbind( wxEVT_MENU, &guMainFrame::OnCommunity, this, ID_MENU_COMMUNITY );
Unbind( wxEVT_MENU, &guMainFrame::OnCopyTracksTo, this, ID_MAINFRAME_COPYTO );
Unbind( wxEVT_MENU, &guMainFrame::OnCopyTracksToDevice, this, ID_MAINFRAME_COPYTODEVICE_TRACKS );
Unbind( wxEVT_MENU, &guMainFrame::OnCopyPlayListToDevice, this, ID_MAINFRAME_COPYTODEVICE_PLAYLIST );
// Unbind( wxEVT_MENU, &guMainFrame::OnUpdateLabels, this, ID_LABEL_UPDATELABELS );
Unbind( wxEVT_MENU, &guMainFrame::OnCreateNewLayout, this, ID_MENU_LAYOUT_CREATE );
Unbind( wxEVT_MENU, &guMainFrame::OnLoadLayout, this, ID_MENU_LAYOUT_LOAD, ID_MENU_LAYOUT_LOAD + 99 );
Unbind( wxEVT_MENU, &guMainFrame::OnDeleteLayout, this, ID_MENU_LAYOUT_DELETE, ID_MENU_LAYOUT_DELETE + 99 );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_PLAYLIST );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_FILTERS );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_VUMETERS );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_PLAYER_NOTEBOOK );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_MAIN_LOCATIONS );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerShowPanel, this, ID_MENU_VIEW_MAIN_SHOWCOVER );
Unbind( wxEVT_MENU, &guMainFrame::OnViewRadio, this, ID_MENU_VIEW_RADIO );
Unbind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_TEXTSEARCH );
Unbind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_LABELS );
Unbind( wxEVT_MENU, &guMainFrame::OnRadioShowPanel, this, ID_MENU_VIEW_RAD_GENRES );
Unbind( wxEVT_MENU, &guMainFrame::OnRadioProperties, this, ID_MENU_VIEW_RAD_PROPERTIES );
Unbind( wxEVT_MENU, &guMainFrame::OnViewLastFM, this, ID_MENU_VIEW_LASTFM );
Unbind( wxEVT_MENU, &guMainFrame::OnViewLyrics, this, ID_MENU_VIEW_LYRICS );
Unbind( wxEVT_MENU, &guMainFrame::OnViewAudioCD, this, ID_MENU_VIEW_AUDIOCD );
Unbind( wxEVT_MENU, &guMainFrame::OnViewPodcasts, this, ID_MENU_VIEW_PODCASTS );
Unbind( wxEVT_MENU, &guMainFrame::OnPodcastsShowPanel, this, ID_MENU_VIEW_POD_CHANNELS );
Unbind( wxEVT_MENU, &guMainFrame::OnPodcastsShowPanel, this, ID_MENU_VIEW_POD_DETAILS );
Unbind( wxEVT_MENU, &guMainFrame::OnPodcastsProperties, this, ID_MENU_VIEW_POD_PROPERTIES );
Unbind( wxEVT_MENU, &guMainFrame::OnViewFileBrowser, this, ID_MENU_VIEW_FILEBROWSER );
Unbind( wxEVT_MENU, &guMainFrame::OnLibraryCoverChanged, this, ID_ALBUM_COVER_CHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayerPanelCoverChanged, this, ID_PLAYERPANEL_COVERUPDATED );
Unbind( wxEVT_MENU, &guMainFrame::OnViewFullScreen, this, ID_MENU_VIEW_FULLSCREEN );
Unbind( wxEVT_MENU, &guMainFrame::OnViewStatusBar, this, ID_MENU_VIEW_STATUSBAR );
Unbind( wxEVT_MENU, &guMainFrame::OnMountMonitorUpdated, this, ID_VOLUMEMANAGER_MOUNT_CHANGED );
Unbind( wxEVT_MENU, &guMainFrame::OnGaugeCreate, this, ID_STATUSBAR_GAUGE_CREATE );
Unbind( wxEVT_MENU, &guMainFrame::OnGaugePulse, this, ID_STATUSBAR_GAUGE_PULSE );
Unbind( wxEVT_MENU, &guMainFrame::OnGaugeSetMax, this, ID_STATUSBAR_GAUGE_SETMAX );
Unbind( wxEVT_MENU, &guMainFrame::OnGaugeUpdate, this, ID_STATUSBAR_GAUGE_UPDATE );
Unbind( wxEVT_MENU, &guMainFrame::OnGaugeRemove, this, ID_STATUSBAR_GAUGE_REMOVE );
Unbind( wxEVT_MENU, &guMainFrame::OnPlayListUpdated, this, ID_PLAYLIST_UPDATED );
Unbind( guPodcastEvent, &guMainFrame::OnPodcastItemUpdated, this, ID_PODCASTS_ITEM_UPDATED );
Unbind( wxEVT_MENU, &guMainFrame::OnRemovePodcastThread, this, ID_MAINFRAME_REMOVEPODCASTTHREAD );
Unbind( wxEVT_MENU, &guMainFrame::OnSetForceGapless, this, ID_MAINFRAME_SETFORCEGAPLESS );
Unbind( wxEVT_MENU, &guMainFrame::OnSetAudioScrobble, this, ID_MAINFRAME_SETAUDIOSCROBBLE );
m_AuiManager.Unbind( wxEVT_AUI_PANE_CLOSE, &guMainFrame::OnMainPaneClose, this );
m_MainNotebook->Unbind( wxEVT_AUINOTEBOOK_PAGE_CHANGED, &guMainFrame::OnPageChanged, this );
m_MainNotebook->Unbind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &guMainFrame::OnPageClosed, this );
Unbind( wxEVT_MENU, &guMainFrame::OnUpdateSelInfo, this, ID_MAINFRAME_UPDATE_SELINFO );
Unbind( wxEVT_MENU, &guMainFrame::OnRequestCurrentTrack, this, ID_MAINFRAME_REQUEST_CURRENTTRACK );
Unbind( wxEVT_MENU, &guMainFrame::OnLyricFound, this, ID_LYRICS_LYRICFOUND );
Unbind( wxEVT_MENU, &guMainFrame::OnLyricSearchFirst, this, ID_MAINFRAME_LYRICSSEARCHFIRST );
Unbind( wxEVT_MENU, &guMainFrame::OnLyricSearchNext, this, ID_MAINFRAME_LYRICSSEARCHNEXT );
Unbind( wxEVT_MENU, &guMainFrame::OnLyricSaveChanges, this, ID_MAINFRAME_LYRICSSAVECHANGES );
Unbind( wxEVT_MENU, &guMainFrame::OnLyricExecCommand, this, ID_MAINFRAME_LYRICSEXECCOMMAND );
Unbind( guConfigUpdatedEvent, &guMainFrame::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guMainFrame::OnSongSetRating, this, ID_PLAYERPANEL_SETRATING_0, ID_PLAYERPANEL_SETRATING_5 );
Unbind( wxEVT_MENU, &guMainFrame::OnRaiseWindow, this, ID_MAINFRAME_WINDOW_RAISE );
Unbind( wxEVT_MENU, &guMainFrame::OnLoadPlayList, this, ID_MAINFRAME_LOAD_PLAYLIST );
Unbind( wxEVT_MENU, &guMainFrame::OnViewPortableDevice, this, ID_MENU_VIEW_PORTABLE_DEVICE, ID_MENU_VIEW_PORTABLE_DEVICE + 99 );
Unbind( wxEVT_MENU, &guMainFrame::OnCollectionCommand, this, ID_COLLECTIONS_BASE, ID_COLLECTIONS_BASE + ( guCOLLECTION_ACTION_COUNT * guCOLLECTIONS_MAXCOUNT ) );
Unbind( wxEVT_MENU, &guMainFrame::OnUpdateRadio, this, ID_RADIO_DOUPDATE );
Unbind( wxEVT_MENU, &guMainFrame::OnMediaViewerClosed, this, ID_MAINFRAME_MEDIAVIEWER_CLOSED );
}
extern void wxClearGtkSystemObjects();
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnSysColorChanged( wxSysColourChangedEvent &event )
//{
// guLogMessage( wxT( "Clear syssettings cache" ) );
// wxClearGtkSystemObjects();
// event.Skip();
//}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnMountMonitorUpdated( wxCommandEvent &event )
{
guLogMessage( wxT( "guMainFrame::OnMountMonitorUpdated" ) );
// a mount point have been removed
if( !event.GetInt() )
{
guLogMessage( wxT( "It was unmounted..." ) );
GMount * Mount = ( GMount * ) event.GetClientData();
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
guMediaViewer * MediaViewer = m_MediaViewers[ Index ];
int Type = MediaViewer->GetType();
if( ( Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( Type == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
if( ( ( guMediaViewerPortableDeviceBase * ) MediaViewer )->IsMount( Mount ) )
{
event.SetId( MediaViewer->GetBaseCommand() );
event.SetInt( 0 );
AddPendingEvent( event );
break;
}
}
}
}
CollectionsUpdated();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnAudioCdVolumeUpdated( wxCommandEvent &event )
{
guLogMessage( wxT( "guMainFrame::OnCdAudioVolumeUpdated" ) );
if( m_AudioCdPanel )
{
m_AudioCdPanel->UpdateVolume( event.GetInt() );
}
}
// -------------------------------------------------------------------------------- //
guMediaViewer * guMainFrame::FindCollectionMediaViewer( const wxString &uniqueid )
{
//guLogMessage( wxT( "FindCollectionMediaViewer( '%s' )" ), uniqueid.c_str() );
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
//guLogMessage( wxT( "Collection[ %i/%i ] -> '%s'" ), Index, Count, m_MediaViewers[ Index ]->GetMediaCollection()->m_UniqueId.c_str() );
if( m_MediaViewers[ Index ]->GetMediaCollection()->m_UniqueId == uniqueid )
return m_MediaViewers[ Index ];
}
return NULL;
}
// -------------------------------------------------------------------------------- //
int guMainFrame::GetMediaViewerIndex( guMediaViewer * mediaviewer )
{
//guLogMessage( wxT( "FindCollectionMediaViewer( '%s' )" ), uniqueid.c_str() );
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_MediaViewers[ Index ] == mediaviewer )
return Index;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
guMediaViewer * guMainFrame::GetDefaultMediaViewer( void )
{
//guLogMessage( wxT( "FindCollectionMediaViewer( '%s' )" ), uniqueid.c_str() );
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_MediaViewers[ Index ]->IsDefault() )
return m_MediaViewers[ Index ];
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guMediaCollection * guMainFrame::FindCollection( const wxString &uniqueid )
{
int Count = m_Collections.Count();
for( int Index = 0; Index < Count; Index++ )
{
guMediaCollection &Collection = m_Collections[ Index ];
if( Collection.m_UniqueId == uniqueid )
return &Collection;
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guMediaViewer * guMainFrame::FindCollectionMediaViewer( void * windowptr )
{
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_MediaViewers[ Index ] == windowptr )
return ( guMediaViewer * ) windowptr;
}
return NULL;
}
// -------------------------------------------------------------------------------- //
int FindCollectionUniqueId( guMediaCollectionArray * collections, const wxString &uniqueid )
{
int Count = collections->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( collections->Item( Index ).m_UniqueId == uniqueid )
return Index;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
wxString guMainFrame::GetCollectionIconString( const wxString &uniqueid )
{
guMediaViewerPortableDeviceBase * MediaViewer = ( guMediaViewerPortableDeviceBase * ) FindCollectionMediaViewer( uniqueid );
if( MediaViewer )
{
return MediaViewer->GetPortableMediaDevice()->IconString();
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CollectionsUpdated( void )
{
CreateCollectionsMenu( m_MenuCollections );
if( m_LocationPanel )
{
m_LocationPanel->CollectionsUpdated();
}
if( m_FileBrowserPanel )
{
m_FileBrowserPanel->CollectionsUpdated();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateCollectionsMenu( wxMenu * menu )
{
wxMutexLocker Locker( m_CollectionsMutex );
wxMenuItem * MenuItem;
int CollectionBaseCommand = ID_COLLECTIONS_BASE;
while( menu->GetMenuItemCount() )
{
menu->Destroy( menu->FindItemByPosition( 0 ) );
}
// MenuItem = new wxMenuItem( menu, -1, _( "Local Music" ), wxEmptyString, wxITEM_NORMAL );
// menu->Append( MenuItem );
// MenuItem->Enable( false );
MenuItem = new wxMenuItem( menu, ID_MENU_COLLECTION_NEW, _( "New Collection" ), _( "Create a new collection" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
//CollectionBaseCommand = ID_COLLECTIONS_BASE;
int Count = m_Collections.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Collections[ Index ].m_Type == guMEDIA_COLLECTION_TYPE_NORMAL )
{
CreateCollectionMenu( menu, m_Collections[ Index ], CollectionBaseCommand );
}
CollectionBaseCommand += guCOLLECTION_ACTION_COUNT;
}
//
// File Browser
m_MenuFileBrowser = new wxMenuItem( menu, ID_MENU_VIEW_FILEBROWSER,
wxString( _( "File Browser" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_FILEBROWSER ),
_( "Show/Hide the file browser panel" ), wxITEM_CHECK );
menu->Append( m_MenuFileBrowser );
m_MenuFileBrowser->Check( m_FileBrowserPanel );
menu->AppendSeparator();
// MenuItem = new wxMenuItem( menu, -1, _( "Online Music" ), wxEmptyString, wxITEM_NORMAL );
// menu->Append( MenuItem );
// MenuItem->Enable( false );
//
// Radio
wxMenu * SubMenu = new wxMenu();
m_MenuRadios = new wxMenuItem( SubMenu, ID_MENU_VIEW_RADIO,
wxString( _( "Show" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_RADIO ),
_( "Show/Hide the radio panel" ), wxITEM_CHECK );
SubMenu->Append( m_MenuRadios );
m_MenuRadios->Check( m_VisiblePanels & guPANEL_MAIN_RADIOS );
SubMenu->AppendSeparator();
m_MenuRadTextSearch = new wxMenuItem( SubMenu, ID_MENU_VIEW_RAD_TEXTSEARCH, _( "Text Search" ), _( "Show/Hide the radio text search" ), wxITEM_CHECK );
SubMenu->Append( m_MenuRadTextSearch );
m_MenuRadTextSearch->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_TEXTSEARCH ) );
m_MenuRadTextSearch->Enable( m_VisiblePanels & guPANEL_MAIN_RADIOS );
// m_MenuRadLabels = new wxMenuItem( SubMenu, ID_MENU_VIEW_RAD_LABELS, _( "Labels" ), _( "Show/Hide the radio labels" ), wxITEM_CHECK );
// SubMenu->Append( m_MenuRadLabels );
// m_MenuRadLabels->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_LABELS ) );
// m_MenuRadLabels->Enable( m_VisiblePanels & guPANEL_MAIN_RADIOS );
m_MenuRadGenres = new wxMenuItem( SubMenu, ID_MENU_VIEW_RAD_GENRES, _( "Genres" ), _( "Show/Hide the radio genres" ), wxITEM_CHECK );
SubMenu->Append( m_MenuRadGenres );
m_MenuRadGenres->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_GENRES ) );
m_MenuRadGenres->Enable( m_VisiblePanels & guPANEL_MAIN_RADIOS );
SubMenu->AppendSeparator();
MenuItem = new wxMenuItem( SubMenu, ID_RADIO_DOUPDATE, _( "Update" ), _( "Update the radio stations" ) );
SubMenu->Append( MenuItem );
MenuItem->Enable( m_VisiblePanels & guPANEL_MAIN_RADIOS );
SubMenu->AppendSeparator();
MenuItem = new wxMenuItem( SubMenu, ID_MENU_VIEW_RAD_PROPERTIES,
_( "Properties" ),
_( "Set the radio preferences" ), wxITEM_NORMAL );
SubMenu->Append( MenuItem );
menu->AppendSubMenu( SubMenu, _( "Radio" ), _( "Set the radio visible panels" ) );
//
// Podcasts
SubMenu = new wxMenu();
m_MenuPodcasts = new wxMenuItem( SubMenu, ID_MENU_VIEW_PODCASTS,
wxString( _( "Show" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_PODCASTS ),
_( "Show/Hide the podcasts panel" ), wxITEM_CHECK );
SubMenu->Append( m_MenuPodcasts );
m_MenuPodcasts->Check( m_VisiblePanels & guPANEL_MAIN_PODCASTS );
SubMenu->AppendSeparator();
m_MenuPodChannels = new wxMenuItem( SubMenu, ID_MENU_VIEW_POD_CHANNELS, _( "Channels" ), _( "Show/Hide the podcasts channels" ), wxITEM_CHECK );
SubMenu->Append( m_MenuPodChannels );
m_MenuPodChannels->Check( m_PodcastsPanel && m_PodcastsPanel->IsPanelShown( guPANEL_PODCASTS_CHANNELS ) );
m_MenuPodChannels->Enable( m_VisiblePanels & guPANEL_MAIN_PODCASTS );
m_MenuPodDetails = new wxMenuItem( SubMenu, ID_MENU_VIEW_POD_DETAILS, _( "Details" ), _( "Show/Hide the podcasts details" ), wxITEM_CHECK );
SubMenu->Append( m_MenuPodDetails );
m_MenuPodDetails->Check( m_PodcastsPanel && m_PodcastsPanel->IsPanelShown( guPANEL_PODCASTS_DETAILS ) );
m_MenuPodDetails->Enable( m_VisiblePanels & guPANEL_MAIN_PODCASTS );
SubMenu->AppendSeparator();
m_MenuPodUpdate = new wxMenuItem( SubMenu, ID_MENU_UPDATE_PODCASTS,
wxString( _( "Update" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_UPDATE_PODCASTS ),
_( "Update the podcasts added" ), wxITEM_NORMAL );
SubMenu->Append( m_MenuPodUpdate );
m_MenuPodUpdate->Enable( m_VisiblePanels & guPANEL_MAIN_PODCASTS );
SubMenu->AppendSeparator();
MenuItem = new wxMenuItem( SubMenu, ID_MENU_VIEW_POD_PROPERTIES,
_( "Properties" ),
_( "Set the podcasts preferences" ), wxITEM_NORMAL );
SubMenu->Append( MenuItem );
menu->AppendSubMenu( SubMenu, _( "Podcasts" ), _( "Set the podcasts visible panels" ) );
CollectionBaseCommand = ID_COLLECTIONS_BASE;
for( int Index = 0; Index < Count; Index++ )
{
if( ( m_Collections[ Index ].m_Type == guMEDIA_COLLECTION_TYPE_JAMENDO ) ||
( m_Collections[ Index ].m_Type == guMEDIA_COLLECTION_TYPE_MAGNATUNE ) )
{
CreateCollectionMenu( menu, m_Collections[ Index ], CollectionBaseCommand, m_Collections[ Index ].m_Type );
}
CollectionBaseCommand += guCOLLECTION_ACTION_COUNT;
}
MenuItem = new wxMenuItem( menu, ID_MENU_PLAY_STREAM,
wxString( _( "Play Stream" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_PLAY_STREAM ),
_( "Play a online music stream" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
m_MenuAudioCD = new wxMenuItem( menu, ID_MENU_VIEW_AUDIOCD, _( "Audio CD" ), _( "View the audio cd panel" ), wxITEM_CHECK );
menu->Append( m_MenuAudioCD );
int PortableDeviceMenuCount = 0;
CollectionBaseCommand = ID_COLLECTIONS_BASE;
for( int Index = 0; Index < Count; Index++ )
{
if( ( m_Collections[ Index ].m_Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( m_Collections[ Index ].m_Type == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
CreateCollectionMenu( menu, m_Collections[ Index ], CollectionBaseCommand, m_Collections[ Index ].m_Type );
PortableDeviceMenuCount++;
}
CollectionBaseCommand += guCOLLECTION_ACTION_COUNT;
}
//
if( m_VolumeMonitor )
{
Count = m_VolumeMonitor->GetMountCount();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
guGIO_Mount * Mount = m_VolumeMonitor->GetMount( Index );
guLogMessage( wxT( "Mount: '%s' => '%s'" ), Mount->GetName().c_str(), Mount->GetMountPath().c_str() );
if( FindCollectionUniqueId( &m_Collections, Mount->GetId() ) == wxNOT_FOUND )
{
MenuItem = new wxMenuItem( menu, ID_MENU_VIEW_PORTABLE_DEVICE + Index, Mount->GetName(), _( "Show the selected portable devices" ), wxITEM_NORMAL );
menu->Append( MenuItem );
}
}
}
else if( !PortableDeviceMenuCount )
{
MenuItem = new wxMenuItem( menu, -1, _( "No Device Found" ), _( "No portable device was detected" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem->Enable( false );
}
}
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_MENU_QUIT,
wxString( _( "Quit" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_QUIT ),
_( "Exits the application" ), wxITEM_NORMAL );
menu->Append( MenuItem );
}
// -------------------------------------------------------------------------------- //
bool guMainFrame::IsCollectionPresent( const wxString &uniqueid )
{
return m_VolumeMonitor && m_VolumeMonitor->GetMountById( uniqueid );
}
// -------------------------------------------------------------------------------- //
bool guMainFrame::IsCollectionActive( const wxString &uniqueid )
{
guMediaViewer * MediaViewer = FindCollectionMediaViewer( uniqueid );
return MediaViewer && ( MediaViewer->GetViewMode() != guMEDIAVIEWER_MODE_NONE );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateCollectionMenu( wxMenu * menu, const guMediaCollection &collection, const int basecommand, int collectiontype )
{
wxMenu * Menu = new wxMenu();
//guLogMessage( wxT( "CreateCollectionMenu( '%s' : '%s' )" ), collection.m_UniqueId.c_str(), collection.m_Name.c_str() );
guMediaViewer * MediaViewer = FindCollectionMediaViewer( collection.m_UniqueId );
int ViewMode = MediaViewer ? MediaViewer->GetViewMode() : guMEDIAVIEWER_MODE_NONE;
bool IsEnabled;
bool IsPresent = true;
if( ( collectiontype == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( collectiontype == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
guGIO_Mount * Mount = NULL;
if( m_VolumeMonitor )
Mount = m_VolumeMonitor->GetMountById( collection.m_UniqueId );
if( !Mount )
IsPresent = false;
}
IsEnabled = IsPresent && ( ViewMode != guMEDIAVIEWER_MODE_NONE );
int VisiblePanels = 0;
if( MediaViewer && ( ViewMode == guMEDIAVIEWER_MODE_LIBRARY ) )
{
VisiblePanels = MediaViewer->GetLibPanel()->VisiblePanels();
}
wxMenuItem * MenuItem = new wxMenuItem( menu, basecommand, _( "Show" ), _( "Open the music collection" ), wxITEM_CHECK );
Menu->Append( MenuItem );
MenuItem->Check( IsEnabled );
MenuItem->Enable( IsPresent );
Menu->AppendSeparator();
//
//
if( IsEnabled )
{
wxMenu * SubMenu = new wxMenu();
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIBRARY, _( "Show" ), _( "View the collection library" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
//MenuItem->Enable( IsEnabled );
MenuItem->Check( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
SubMenu->AppendSeparator();
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_LABELS, _( "Labels" ), _( "View the library labels" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_LABELS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_GENRES, _( "Genres" ), _( "View the library genres" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_GENRES );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_ARTISTS, _( "Artists" ), _( "View the library artists" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_ARTISTS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_COMPOSERS, _( "Composers" ), _( "View the library composers" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_COMPOSERS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_ALBUMARTISTS, _( "Album Artists" ), _( "View the library album artists" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_ALBUMARTISTS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_ALBUMS, _( "Albums" ), _( "View the library albums" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_ALBUMS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_YEARS, _( "Years" ), _( "View the library years" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_YEARS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_RATINGS, _( "Ratings" ), _( "View the library ratings" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_RATINGS );
MenuItem = new wxMenuItem( SubMenu, basecommand + guCOLLECTION_ACTION_VIEW_LIB_PLAYCOUNT, _( "Plays" ), _( "View the library play counts" ), wxITEM_CHECK );
SubMenu->Append( MenuItem );
MenuItem->Enable( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
MenuItem->Check( VisiblePanels & guPANEL_LIBRARY_PLAYCOUNT );
Menu->AppendSubMenu( SubMenu, _( "Library" ) );
}
else
{
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_VIEW_LIBRARY, _( "Library" ), _( "View the collection library" ), wxITEM_CHECK );
Menu->Append( MenuItem );
MenuItem->Enable( false );
MenuItem->Check( ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
}
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_VIEW_ALBUMBROWSER, _( "Album Browser" ), _( "View the collection album browser" ), wxITEM_CHECK );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem->Check( ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER );
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_VIEW_TREEVIEW, _( "Tree" ), _( "View the collection tree view" ), wxITEM_CHECK );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem->Check( ViewMode == guMEDIAVIEWER_MODE_TREEVIEW );
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_VIEW_PLAYLISTS, _( "Playlists" ), _( "View the collection playlists" ), wxITEM_CHECK );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem->Check( ViewMode == guMEDIAVIEWER_MODE_PLAYLISTS );
if( ( collection.m_Type == guMEDIA_COLLECTION_TYPE_NORMAL ) ||
( collection.m_Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( collection.m_Type == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_ADD_PATH, _( "Add Path" ), _( "Add path to the collection" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_IMPORT, _( "Import Files" ), _( "Import files into the collection" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_UPDATE_LIBRARY,
_( "Update" ),
_( "Update the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_RESCAN_LIBRARY,
_( "Rescan" ),
_( "Rescan the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_SEARCH_COVERS,
_( "Search Covers" ),
_( "Search the collection missing covers" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem->Enable( IsEnabled );
if( ( collectiontype == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) || ( collectiontype == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, basecommand + guCOLLECTION_ACTION_UNMOUNT, _( "Unmount" ), _( "Unmount the device" ) );
Menu->Append( MenuItem );
MenuItem->Enable( IsPresent );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, basecommand + guCOLLECTION_ACTION_VIEW_PROPERTIES, _( "Properties" ), _( "Show collection properties" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
if( ( collectiontype == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) || ( collectiontype == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
MenuItem->Enable( IsEnabled );
}
menu->AppendSubMenu( Menu, collection.m_Name );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateViewMenu( wxMenu * menu )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxMenuItem * MenuItem = new wxMenuItem( menu, ID_MENU_LAYOUT_CREATE,
wxString( _( "Save Layout" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_LAYOUT_CREATE ),
_( "Saves the current layout" ) );
menu->Append( MenuItem );
CreateLayoutMenus( menu );
menu->AppendSeparator();
//
// Player PlayList
m_MenuPlayerPlayList = new wxMenuItem( menu, ID_MENU_VIEW_PLAYER_PLAYLIST,
wxString( _( "Player Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_PLAYER_PLAYLIST ),
_( "Show/Hide the player playlist panel" ), wxITEM_CHECK );
menu->Append( m_MenuPlayerPlayList );
m_MenuPlayerPlayList->Check( m_PlayerPlayList );
//
// Locations
m_MenuMainLocations = new wxMenuItem( menu, ID_MENU_VIEW_MAIN_LOCATIONS,
wxString( _( "Sources" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_MAIN_LOCATIONS ),
_( "Show/Hide the locatons" ), wxITEM_CHECK );
menu->Append( m_MenuMainLocations );
m_MenuMainLocations->Check( m_LocationPanel );
//
// Player Filters
m_MenuPlayerFilters = new wxMenuItem( menu, ID_MENU_VIEW_PLAYER_FILTERS,
wxString( _( "Player Filters" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_PLAYER_FILTERS ),
_( "Show/Hide the player filters panel" ), wxITEM_CHECK );
menu->Append( m_MenuPlayerFilters );
m_MenuPlayerFilters->Check( m_PlayerFilters );
//
// Player Vumeters
m_MenuPlayerVumeters = new wxMenuItem( menu, ID_MENU_VIEW_PLAYER_VUMETERS,
wxString( _( "VU Meters" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_PLAYER_VUMETERS ),
_( "Show/Hide the player vumeter" ), wxITEM_CHECK );
menu->Append( m_MenuPlayerVumeters );
m_MenuPlayerVumeters->Check( m_PlayerVumeters );
//
// Main Cover
m_MenuMainShowCover = new wxMenuItem( menu, ID_MENU_VIEW_MAIN_SHOWCOVER,
wxString( _( "Cover" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_MAIN_SHOWCOVER ),
_( "Show/Hide the cover" ), wxITEM_CHECK );
menu->Append( m_MenuMainShowCover );
m_MenuMainShowCover->Check( m_CoverPanel );
menu->AppendSeparator();
//
// Last.fm
m_MenuLastFM = new wxMenuItem( menu, ID_MENU_VIEW_LASTFM,
wxString( _( "Last.fm" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_LASTFM ),
_( "Show/Hide the Last.fm panel" ), wxITEM_CHECK );
menu->Append( m_MenuLastFM );
m_MenuLastFM->Check( m_VisiblePanels & guPANEL_MAIN_LASTFM );
//
// Lyrics
m_MenuLyrics = new wxMenuItem( menu, ID_MENU_VIEW_LYRICS,
wxString( _( "Lyrics" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_LYRICS ),
_( "Show/Hide the lyrics panel" ), wxITEM_CHECK );
menu->Append( m_MenuLyrics );
m_MenuLyrics->Check( m_VisiblePanels & guPANEL_MAIN_LYRICS );
//
// Other options
menu->AppendSeparator();
m_MenuFullScreen = new wxMenuItem( menu, ID_MENU_VIEW_FULLSCREEN,
wxString( _( "Full Screen" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_FULLSCREEN ),
_( "Show/Restore the main window in full screen" ), wxITEM_CHECK );
menu->Append( m_MenuFullScreen );
m_MenuFullScreen->Check( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN, false, CONFIG_PATH_MAIN_WINDOW ) );
m_MenuStatusBar = new wxMenuItem( menu, ID_MENU_VIEW_STATUSBAR,
wxString( _( "Statusbar" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_STATUSBAR ),
_( "Show/Hide the statusbar" ), wxITEM_CHECK );
menu->Append( m_MenuStatusBar );
m_MenuStatusBar->Check( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_STATUS_BAR, true, CONFIG_PATH_MAIN_WINDOW ) );
MenuItem = new wxMenuItem( menu, ID_MENU_HIDE_CAPTIONS,
wxString( _( "Show Captions" ) ),
_( "Show/Hide the windows caption" ), wxITEM_CHECK );
menu->Append( MenuItem );
MenuItem->Check( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_CAPTIONS, true, CONFIG_PATH_MAIN_WINDOW ) );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_MENU_VIEW_CLOSEWINDOW,
wxString( _( "Close Current Tab" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VIEW_CLOSEWINDOW ),
_( "Close the current selected tab" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_MENU_PREFERENCES,
wxString( _( "Preferences" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_PREFERENCES ),
_( "View the preferences" ), wxITEM_NORMAL );
menu->Append( MenuItem );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateLayoutMenus( wxMenu * menu )
{
m_MenuLayoutLoad = new wxMenu();
m_MenuLayoutDelete = new wxMenu();
menu->AppendSubMenu( m_MenuLayoutLoad, _( "Load Layout" ), _( "Set current view from a user defined layout" ) );
menu->AppendSubMenu( m_MenuLayoutDelete, _( "Delete Layout" ), _( "Delete a user defined layout" ) );
ReloadLayoutMenus();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateControlsMenu( wxMenu * menu )
{
wxMenuItem * MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_NEXTTRACK,
wxString( _( "Next Track" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_NEXTTRACK ),
_( "Play the next track in the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_PREVTRACK,
wxString( _( "Prev. Track" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_PREVTRACK ),
_( "Play the previous track in the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_NEXTALBUM,
wxString( _( "Next Album" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_NEXTALBUM ),
_( "Play the next album in the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_PREVALBUM,
wxString( _( "Prev. Album" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_PREVALBUM ),
_( "Play the previous album in the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_PLAY ),
_( "Play or Pause the current track in the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_PLAYERPANEL_STOP,
wxString( _( "Stop" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_STOP ),
_( "Stop the current played track" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_PLAYER_PLAYLIST_STOP_ATEND,
wxString( _( "Stop at End" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_STOP_ATEND ),
_( "Stop after current playing or selected track" ) );
menu->Append( MenuItem );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_PLAYER_PLAYLIST_CLEAR,
wxString( _( "Clear Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_CLEAR ),
_( "Clear the now playing playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
wxMenu * RatingMenu = new wxMenu();
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_0,
wxT( "☆☆☆☆☆" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_0 ),
_( "Set the rating to 0" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_1,
wxT( "★☆☆☆☆" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_1 ),
_( "Set the rating to 1" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_2,
wxT( "★★☆☆☆" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_2 ),
_( "Set the rating to 2" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_3,
wxT( "★★★☆☆" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_3 ),
_( "Set the rating to 3" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_4,
wxT( "★★★★☆" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_4 ),
_( "Set the rating to 4" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_5,
wxT( "★★★★★" ) + guAccelGetCommandKeyCodeString( ID_PLAYERPANEL_SETRATING_5 ),
_( "Set the rating to 5" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
menu->AppendSubMenu( RatingMenu, _( "Set Rating" ), _( "Set the rating of the current track" ) );
menu->AppendSeparator();
m_MenuPlaySmart = new wxMenuItem( menu, ID_PLAYER_PLAYMODE_SMART,
wxString( _( "Smart Play" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYMODE_SMART ),
_( "Update playlist based on Last.fm statics" ), wxITEM_CHECK );
menu->Append( m_MenuPlaySmart );
m_MenuPlaySmart->Check( m_PlayerPanel->GetPlaySmart() );
MenuItem = new wxMenuItem( menu, ID_PLAYER_PLAYLIST_RANDOMPLAY,
wxString( _( "Randomize" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_RANDOMPLAY ),
_( "Randomize the playlist" ), wxITEM_NORMAL );
menu->Append( MenuItem );
m_MenuLoopPlayList = new wxMenuItem( menu, ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST,
wxString( _( "Repeat Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST ),
_( "Repeat the tracks in the playlist" ), wxITEM_CHECK );
menu->Append( m_MenuLoopPlayList );
m_MenuLoopPlayList->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
m_MenuLoopTrack = new wxMenuItem( menu, ID_PLAYER_PLAYMODE_REPEAT_TRACK,
wxString( _( "Repeat Track" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYMODE_REPEAT_TRACK ),
_( "Repeat the current track in the playlist" ), wxITEM_CHECK );
menu->Append( m_MenuLoopTrack );
m_MenuLoopTrack->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_TRACK );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_MENU_VOLUME_UP,
wxString( _( "Volume Up" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VOLUME_UP ),
_( "Increment the volume level" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_MENU_VOLUME_DOWN,
wxString( _( "Volume Down" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_VOLUME_DOWN ),
_( "Decrement the volume level" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
m_MenuForceGapless = new wxMenuItem( menu, ID_MAINFRAME_SETFORCEGAPLESS,
wxString( _( "Force Gapless Mode" ) ) + guAccelGetCommandKeyCodeString( ID_MAINFRAME_SETFORCEGAPLESS ),
_( "Set playback in gapless mode" ), wxITEM_CHECK );
menu->Append( m_MenuForceGapless );
m_MenuForceGapless->Check( m_PlayerPanel->GetForceGapless() );
m_MenuAudioScrobble = new wxMenuItem( menu, ID_MAINFRAME_SETAUDIOSCROBBLE,
wxString( _( "Audioscrobble" ) ) + guAccelGetCommandKeyCodeString( ID_MAINFRAME_SETAUDIOSCROBBLE ),
_( "Send played tracks information" ), wxITEM_CHECK );
menu->Append( m_MenuAudioScrobble );
m_MenuAudioScrobble->Check( m_PlayerPanel->GetAudioScrobbleEnabled() );
}
//// -------------------------------------------------------------------------------- //
//void guMainFrame::CreateActionsMenu( wxMenu * menu )
//{
// //menu->AppendSeparator();
//}
//
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateHelpMenu( wxMenu * menu )
{
wxMenuItem * MenuItem = new wxMenuItem( menu, ID_MENU_HELP,
wxString( _( "Help" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_HELP ),
_( "Get help using guayadeque" ), wxITEM_NORMAL );
menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_MENU_COMMUNITY,
wxString( _( "Community" ) ) + guAccelGetCommandKeyCodeString( ID_MENU_COMMUNITY ),
_( "Get guayadeque support from guayadeque.org" ), wxITEM_NORMAL );
menu->Append( MenuItem );
menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, ID_MENU_ABOUT,
_( "About" ),
_( "Show information about guayadeque music player" ), wxITEM_NORMAL );
menu->Append( MenuItem );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateMenu()
{
wxMenuBar * MenuBar;
wxMenu * MenuEntry;
// Create the main Menu Bar
MenuBar = new wxMenuBar( 0 );
//
// Now create the Collections Menu Entry
m_MenuCollections = new wxMenu();
CreateCollectionsMenu( m_MenuCollections );
MenuBar->Append( m_MenuCollections, _( "Sources" ) );
//
// Now create the View Menu Entry
MenuEntry = new wxMenu();
CreateViewMenu( MenuEntry );
MenuBar->Append( MenuEntry, _( "View" ) );
//
// Now create the Controls Menu Entry
MenuEntry = new wxMenu();
CreateControlsMenu( MenuEntry );
MenuBar->Append( MenuEntry, _( "Controls" ) );
//
// Now create the Help Menu Entry
MenuEntry = new wxMenu();
CreateHelpMenu( MenuEntry );
MenuBar->Append( MenuEntry, _( "Help" ) );
SetMenuBar( MenuBar );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPreferences( wxCommandEvent &event )
{
int Page;
switch( event.GetId() )
{
case ID_MENU_COLLECTION_NEW :
Page = guPREFERENCE_PAGE_LIBRARY;
break;
case ID_MENU_PREFERENCES_COMMANDS :
Page = guPREFERENCE_PAGE_COMMANDS;
break;
case ID_MENU_PREFERENCES_COPYTO :
Page = guPREFERENCE_PAGE_COPYTO;
break;
case ID_MENU_PREFERENCES_LINKS :
Page = guPREFERENCE_PAGE_LINKS;
break;
default :
Page = event.GetInt() ? event.GetInt() : wxNOT_FOUND;
}
guPrefDialog * PrefDialog = new guPrefDialog( this, m_Db, Page );
if( PrefDialog )
{
if( PrefDialog->ShowModal() == wxID_OK )
{
PrefDialog->SaveSettings();
CreateTaskBarIcon();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->SendConfigChangedEvent( PrefDialog->GetVisiblePanels() );
//m_Db->ConfigChanged();
}
PrefDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCloseWindow( wxCloseEvent &event )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( m_MPRIS2->Indicators_Sound_Available() )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_SOUND_MENU_INTEGRATE, false, CONFIG_PATH_GENERAL ) )
{
guMediaState State = m_PlayerPanel->GetState();
if( State == guMEDIASTATE_PLAYING )
{
if( event.CanVeto() )
{
Show( false );
return;
}
}
}
}
else
{
// If the icon
if( m_TaskBarIcon &&
Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_TASK_BAR_ICON, false, CONFIG_PATH_GENERAL ) &&
Config->ReadBool( CONFIG_KEY_GENERAL_CLOSE_TO_TASKBAR, false, CONFIG_PATH_GENERAL ) )
{
if( event.CanVeto() )
{
Show( false );
return;
}
}
else if( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_CONFIRM, true, CONFIG_PATH_GENERAL ) )
{
guExitConfirmDlg * ExitConfirmDlg = new guExitConfirmDlg( this );
if( ExitConfirmDlg )
{
int Result = ExitConfirmDlg->ShowModal();
if( ExitConfirmDlg->GetConfirmChecked() )
{
Config->WriteBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_CONFIRM, false, CONFIG_PATH_GENERAL );
}
ExitConfirmDlg->Destroy();
if( Result != wxID_OK )
return;
}
}
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnUpdateTrack( wxCommandEvent &event )
{
guTrack * Track = ( guTrack * ) event.GetClientData();
if( Track )
{
SetTitle( Track->m_SongName + wxT( " / " ) + Track->m_ArtistName +
wxT( " - Guayadeque Music Player " ID_GUAYADEQUE_VERSION "-" ID_GUAYADEQUE_REVISION ) );
if( m_TaskBarIcon )
{
m_TaskBarIcon->SetIcon( m_AppIcon, wxT( "Guayadeque Music Player " ID_GUAYADEQUE_VERSION \
"-" ID_GUAYADEQUE_REVISION "\r" ) +
Track->m_ArtistName + wxT( "\n" ) +
Track->m_SongName );
}
}
else
{
SetTitle( wxT( "Guayadeque Music Player " ID_GUAYADEQUE_VERSION "-" ID_GUAYADEQUE_REVISION ) );
if( m_TaskBarIcon )
{
m_TaskBarIcon->SetIcon( m_AppIcon, wxT( "Guayadeque Music Player " ID_GUAYADEQUE_VERSION "-" ID_GUAYADEQUE_REVISION ) );
}
}
if( m_LastFMPanel )
{
m_LastFMPanel->OnUpdatedTrack( event );
}
if( m_LyricsPanel )
{
m_LyricsPanel->OnSetCurrentTrack( event );
}
if( m_LyricSearchEngine )
{
if( m_LyricSearchContext )
{
delete m_LyricSearchContext;
m_LyricSearchContext = NULL;
}
if( m_LyricSearchEngine->TargetsEnabled() ||
( m_LyricsPanel && m_LyricsPanel->UpdateEnabled() ) )
{
m_LyricSearchContext = m_LyricSearchEngine->CreateContext( this, Track );
m_LyricSearchEngine->SearchStart( m_LyricSearchContext );
}
}
if( m_MPRIS )
{
m_MPRIS->OnPlayerTrackChange();
}
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerTrackChange();
}
CheckPendingUpdates( Track );
if( Track )
{
delete Track;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerStatusChanged( wxCommandEvent &event )
{
if( m_MPRIS )
{
m_MPRIS->OnPlayerStatusChange();
}
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerStatusChange();
}
if( m_PlayerPanel )
{
m_MenuPlaySmart->Check( m_PlayerPanel->GetPlaySmart() );
m_MenuLoopPlayList->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
m_MenuLoopTrack->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_TRACK );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerTrackListChanged( wxCommandEvent &event )
{
if( m_MPRIS )
{
m_MPRIS->OnTrackListChange();
}
if( m_MPRIS2 )
{
m_MPRIS2->OnTrackListChange();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerCapsChanged( wxCommandEvent &event )
{
if( m_MPRIS )
{
m_MPRIS->OnPlayerCapsChange();
}
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerCapsChange();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerVolumeChanged( wxCommandEvent &event )
{
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerVolumeChange();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerSeeked( wxCommandEvent &event )
{
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerSeeked( event.GetInt() );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnAudioScrobbleUpdate( wxCommandEvent &event )
{
//guLogMessage( wxT( "######## OnAudioScrobbleUpdate ( %i ) ########" ), event.GetInt() );
if( m_MainStatusBar )
{
m_MainStatusBar->UpdateAudioScrobbleIcon( !event.GetInt() );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnQuit( wxCommandEvent &event )
{
CheckPendingUpdates( m_PlayerPanel->GetCurrentTrack(), true );
Close( true );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCloseTab( wxCommandEvent &event )
{
m_CurrentPage = m_MainNotebook->GetPage( m_MainNotebook->GetSelection() );
if( m_CurrentPage )
{
DoPageClose( ( wxPanel * ) m_CurrentPage );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnShowCaptions( wxCommandEvent &event )
{
DoShowCaptions( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::DoShowCaptions( const bool visible )
{
//guLogMessage( wxT( "guMainFrame::OnShowCaptions( %i )" ) );
wxAuiPaneInfoArray &PaneInfoArray = m_AuiManager.GetAllPanes();
int Count = PaneInfoArray.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxAuiPaneInfo &PaneInfo = PaneInfoArray[ Index ];
if( PaneInfo.dock_direction != wxAUI_DOCK_CENTER )
{
if( PaneInfo.name == wxT( "PlayerPlayList" ) )
continue;
PaneInfo.CaptionVisible( visible );
}
}
m_AuiManager.Update();
//
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteBool( CONFIG_KEY_MAIN_WINDOW_CAPTIONS, visible, CONFIG_PATH_MAIN_WINDOW );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnChangeVolume( wxCommandEvent &event )
{
if( m_PlayerPanel )
{
double CurVolume = m_PlayerPanel->GetVolume();
//guLogMessage( wxT( "CurVolume: %.2f" ), CurVolume );
m_PlayerPanel->SetVolume( ( event.GetId() == ID_MENU_VOLUME_UP ) ? CurVolume + 4 : CurVolume - 4 );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayStream( wxCommandEvent &event )
{
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Stream:" ),
_( "Play Stream" ), wxEmptyString );
if( EntryDialog->ShowModal() == wxID_OK && !EntryDialog->GetValue().IsEmpty() )
{
wxArrayString Streams;
Streams.Add( EntryDialog->GetValue() );
m_PlayerPanel->SetPlayList( Streams );
}
EntryDialog->Destroy();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnUpdatePodcasts( wxCommandEvent& WXUNUSED(event) )
{
UpdatePodcasts();
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnPlay( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnPlayButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnStop( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnStopButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnStopAtEnd( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnStopAtEnd( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnClearPlaylist( wxCommandEvent &event )
{
if( m_PlayerPlayList )
{
m_PlayerPlayList->GetPlayListCtrl()->ClearItems();
}
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnNextTrack( wxCommandEvent &event )
{
event.SetInt( 0 );
if( m_PlayerPanel )
m_PlayerPanel->OnNextTrackButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnPrevTrack( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnPrevTrackButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnNextAlbum( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnNextAlbumButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnPrevAlbum( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnPrevAlbumButtonClick( event );
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnPlayMode( wxCommandEvent &event )
{
if( m_PlayerPanel )
{
int PlayMode = guPLAYER_PLAYMODE_NONE;
switch( event.GetId() )
{
case ID_PLAYER_PLAYMODE_SMART :
PlayMode = m_PlayerPanel->GetPlaySmart() ? guPLAYER_PLAYMODE_NONE : guPLAYER_PLAYMODE_SMART;
break;
case ID_PLAYER_PLAYMODE_REPEAT_PLAYLIST :
PlayMode = guPLAYER_PLAYMODE_REPEAT_PLAYLIST;
break;
case ID_PLAYER_PLAYMODE_REPEAT_TRACK :
PlayMode = guPLAYER_PLAYMODE_REPEAT_TRACK;
break;
}
m_PlayerPanel->SetPlayMode( PlayMode );
m_MenuPlaySmart->Check( m_PlayerPanel->GetPlaySmart() );
m_MenuLoopPlayList->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
m_MenuLoopTrack->Check( m_PlayerPanel->GetPlayMode() == guPLAYER_PLAYMODE_REPEAT_TRACK );
}
}
// ---------------------------------------------------------------------- //
void guMainFrame::OnRandomize( wxCommandEvent &event )
{
if( m_PlayerPanel )
m_PlayerPanel->OnRandomPlayButtonClick( event );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnAbout( wxCommandEvent &event )
{
guSplashFrame * SplashFrame = new guSplashFrame( this, 10000 );
if( !SplashFrame )
{
guLogError( wxT( "Could not create the splash screen window" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnHelp( wxCommandEvent &event )
{
guWebExecute( wxT( "https://github.com/anonbeat/guayadeque/wiki" ) );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCommunity( wxCommandEvent &event )
{
guWebExecute( wxT( "http://guayadeque.org" ) );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerPlayListUpdateTitle( wxCommandEvent &event )
{
//guLogMessage( wxT( "OnPlayerPlayListUPdateTitle..." ) );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( wxT( "PlayerPlayList" ) );
if( PaneInfo.IsOk() )
{
//guLogMessage( wxT( "Updating PlayListTitle..." ) );
guPlayList * PlayList = m_PlayerPlayList->GetPlayListCtrl();
PaneInfo.Caption( _( "Now Playing" ) +
wxString::Format( wxT( ": %i / %li ( %s )" ),
PlayList->GetCurItem() + 1,
PlayList->GetCount(),
PlayList->GetLengthStr().c_str() ) );
m_AuiManager.Update();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCopyTracksTo( wxCommandEvent &event )
{
guTrackArray * Tracks = ( guTrackArray * ) event.GetClientData();
if( Tracks )
{
if( Tracks->Count() )
{
m_CopyToThreadMutex.Lock();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString CopyToOptions = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
wxArrayString SelCopyTo = wxStringTokenize( CopyToOptions[ event.GetInt() ], wxT( ":") );
while( SelCopyTo.Count() != 6 )
SelCopyTo.Add( wxEmptyString );
wxString DestDir = SelCopyTo[ 5 ];
if( DestDir.IsEmpty() )
{
wxDirDialog * DirDialog = new wxDirDialog( this,
_( "Select destination directory" ), wxGetHomeDir(), wxDD_DIR_MUST_EXIST );
if( DirDialog )
{
if( DirDialog->ShowModal() == wxID_OK )
{
DestDir = DirDialog->GetPath() + wxT( "/" );
}
DirDialog->Destroy();
}
}
if( !DestDir.IsEmpty() )
{
if( !m_CopyToThread )
{
int GaugeId = m_MainStatusBar->AddGauge( _( "Copy To..." ), false );
m_CopyToThread = new guCopyToThread( this, GaugeId );
}
guMediaViewer * MediaViewer = Tracks->Item( 0 ).m_MediaViewer;
m_CopyToThread->AddAction( Tracks, MediaViewer, DestDir,
unescape_configlist_str( SelCopyTo[ 1 ] ),
wxAtoi( SelCopyTo[ 2 ] ),
wxAtoi( SelCopyTo[ 3 ] ),
wxAtoi( SelCopyTo[ 4 ] ) );
}
else
{
delete Tracks;
}
m_CopyToThreadMutex.Unlock();
}
else
{
delete Tracks;
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCopyTracksToDevice( wxCommandEvent &event )
{
guLogMessage( wxT( "guMainFrame::OnCopyTracksToDevice... %i" ), event.GetInt() );
guTrackArray * Tracks = ( guTrackArray * ) event.GetClientData();
if( Tracks )
{
if( Tracks->Count() )
{
int PortableIndex = event.GetInt();
if( PortableIndex >= 0 && PortableIndex < ( int ) m_Collections.Count() )
{
guMediaViewer * MediaViewer = m_MediaViewers[ PortableIndex ];
if( MediaViewer )
{
guLogMessage( wxT( "MediaViewer with collection id '%s' for CopyTracks found" ), m_Collections[ PortableIndex ].m_UniqueId.c_str() );
m_CopyToThreadMutex.Lock();
if( !m_CopyToThread )
{
int GaugeId = m_MainStatusBar->AddGauge( _( "Copy To..." ), false );
m_CopyToThread = new guCopyToThread( this, GaugeId );
}
m_CopyToThread->AddAction( Tracks, MediaViewer );
m_CopyToThreadMutex.Unlock();
return;
}
}
else
{
guLogMessage( wxT( "Wrong portable device index in copy tracks to device command" ) );
}
}
delete Tracks;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::ImportFiles( guMediaViewer * mediaviewer, guTrackArray * tracks, const wxString ©tooption, const wxString &destdir )
{
guCopyToPattern * CopyToPattern = NULL;
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString CopyToOptions = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
int Count;
if( ( Count = CopyToOptions.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
if( CopyToOptions[ Index ].BeforeFirst( wxT( ':' ) ) == copytooption )
{
CopyToPattern = new guCopyToPattern( CopyToOptions[ Index ] );
break;
}
}
}
if( CopyToPattern )
{
m_CopyToThreadMutex.Lock();
if( !m_CopyToThread )
{
int GaugeId = m_MainStatusBar->AddGauge( _( "Copy To..." ), false );
m_CopyToThread = new guCopyToThread( this, GaugeId );
}
m_CopyToThread->AddAction( tracks, mediaviewer, destdir,
CopyToPattern->m_Pattern,
CopyToPattern->m_Format,
CopyToPattern->m_Quality,
CopyToPattern->m_MoveFiles );
m_CopyToThreadMutex.Unlock();
delete CopyToPattern;
}
else
{
guLogMessage( wxT( "Could not find the copy to option selected" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCopyPlayListToDevice( wxCommandEvent &event )
{
guLogMessage( wxT( "guMainFrame::OnCopyPlayListToDevice" ) );
wxString * PlayListPath = ( wxString * ) event.GetClientData();
if( PlayListPath )
{
int PortableIndex = event.GetInt();
if( PortableIndex >= 0 && PortableIndex < ( int ) m_Collections.Count() )
{
guMediaViewerPortableDevice * MediaViewer = ( guMediaViewerPortableDevice * ) m_MediaViewers[ PortableIndex ];
if( MediaViewer )
{
m_CopyToThreadMutex.Lock();
if( !m_CopyToThread )
{
int GaugeId = m_MainStatusBar->AddGauge( _( "Copy To..." ), false );
m_CopyToThread = new guCopyToThread( this, GaugeId );
}
m_CopyToThread->AddAction( PlayListPath, MediaViewer );
m_CopyToThreadMutex.Unlock();
}
}
else
{
guLogMessage( wxT( "Wrong portable device index in copy playlist to device command" ) );
}
}
}
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnUpdateLabels( wxCommandEvent &event )
//{
//// if( m_LibPanel )
//// {
//// m_LibPanel->UpdateLabels();
//// }
//}
//// -------------------------------------------------------------------------------- //
//int GetPageIndex( wxAuiNotebook * Notebook, wxPanel * Page )
//{
// int count = Notebook->GetPageCount();
// for( int index = 0; index < count; index++ )
// {
// if( Notebook->GetPage( index ) == Page )
// return index;
// }
// return -1;
//}
// -------------------------------------------------------------------------------- //
void guMainFrame::CheckShowNotebook( void )
{
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
if( !PaneInfo.IsShown() )
{
PaneInfo.Show();
m_AuiManager.Update();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CheckHideNotebook( void )
{
if( !m_MainNotebook->GetPageCount() )
{
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
PaneInfo.Hide();
m_AuiManager.Update();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::RemoveTabPanel( wxPanel * panel )
{
int PageIndex = m_MainNotebook->GetPageIndex( panel );
if( PageIndex != wxNOT_FOUND )
{
if( m_MainNotebook->GetPageCount() > 1 )
{
panel->Hide();
m_MainNotebook->RemovePage( PageIndex );
}
else
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteStr( CONFIG_KEY_MAIN_WINDOW_NOTEBOOK_LAST_LAYOUT, m_AuiManager.SavePerspective(), CONFIG_PATH_MAIN_WINDOW_NOTEBOOK );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
PaneInfo.Hide();
m_AuiManager.Update();
}
}
else
{
guLogError( wxT( "Asked to remove a panel that is not in the tab control" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::InsertTabPanel( wxPanel * panel, const int index, const wxString &label, const wxString &panelid )
{
int PageIndex = m_MainNotebook->GetPageIndex( panel );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
if( !PaneInfo.IsShown() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
LoadPerspective( Config->ReadStr( CONFIG_KEY_MAIN_WINDOW_NOTEBOOK_LAST_LAYOUT, wxEmptyString, CONFIG_PATH_MAIN_WINDOW_NOTEBOOK ) );
wxWindow * OldPage = m_MainNotebook->GetPage( 0 );
// Was hidden
if( PageIndex == wxNOT_FOUND )
{
m_MainNotebook->InsertPage( wxMin( index, ( int ) m_MainNotebook->GetPageCount() ), panel, label, true );
m_MainNotebook->AddId( panel, panelid );
int OldIndex = m_MainNotebook->GetPageIndex( OldPage );
m_MainNotebook->RemovePage( OldIndex );
if( m_DestroyLastWindow )
{
delete ( ( guMediaViewer * ) OldPage );
m_DestroyLastWindow = false;
}
}
PaneInfo.Show();
m_AuiManager.Update();
}
else
{
m_MainNotebook->InsertPage( wxMin( index, ( int ) m_MainNotebook->GetPageCount() ), panel, label, true );
m_MainNotebook->AddId( panel, panelid );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCollectionCommand( wxCommandEvent &event )
{
int CollectionIndex = ( event.GetId() - ID_COLLECTIONS_BASE ) / guCOLLECTION_ACTION_COUNT;
int CollectionCmdId = ( event.GetId() - ID_COLLECTIONS_BASE ) % guCOLLECTION_ACTION_COUNT;
bool IsEnabled = event.IsChecked();
guLogMessage( wxT( "OnCollectionCommand %i %i %i %i" ), event.GetId(), CollectionIndex, CollectionCmdId, IsEnabled );
guMediaCollection &Collection = m_Collections[ CollectionIndex ];
guMediaViewer * MediaViewer = FindCollectionMediaViewer( Collection.m_UniqueId );
if( !MediaViewer )
{
guLogMessage( wxT( "MediaViewer Not Found for '%s'" ), Collection.m_UniqueId.c_str() );
}
else
{
m_MainNotebook->SetSelection( m_MainNotebook->GetPageIndex( MediaViewer ) );
}
switch( CollectionCmdId )
{
case guCOLLECTION_ACTION_VIEW_COLLECTION :
{
if( IsEnabled )
{
if( !MediaViewer )
{
switch( Collection.m_Type )
{
case guMEDIA_COLLECTION_TYPE_NORMAL :
MediaViewer = ( guMediaViewer * ) new guMediaViewerLibrary( m_MainNotebook, Collection, event.GetId(), this, -1, m_PlayerPanel );
break;
case guMEDIA_COLLECTION_TYPE_JAMENDO :
MediaViewer = ( guMediaViewer * ) new guMediaViewerJamendo( m_MainNotebook, Collection, event.GetId(), this, -1, m_PlayerPanel );
break;
case guMEDIA_COLLECTION_TYPE_MAGNATUNE :
MediaViewer = ( guMediaViewer * ) new guMediaViewerMagnatune( m_MainNotebook, Collection, event.GetId(), this, -1, m_PlayerPanel );
break;
case guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE :
{
guGIO_Mount * Mount = m_VolumeMonitor->GetMountById( Collection.m_UniqueId );
MediaViewer = ( guMediaViewer * ) new guMediaViewerPortableDevice( m_MainNotebook, Collection, event.GetId(), this, -1, m_PlayerPanel, Mount );
break;
}
#ifdef WITH_LIBGPOD_SUPPORT
case guMEDIA_COLLECTION_TYPE_IPOD :
{
guGIO_Mount * Mount = m_VolumeMonitor->GetMountById( Collection.m_UniqueId );
MediaViewer = ( guMediaViewer * ) new guMediaVieweriPodDevice( m_MainNotebook, Collection, event.GetId(), this, -1, m_PlayerPanel, Mount );
break;
}
#endif
}
m_MediaViewers.Add( MediaViewer );
}
if( MediaViewer->IsDefault() && ( MediaViewer->GetViewMode() == guMEDIAVIEWER_MODE_NONE ) )
{
MediaViewer->SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
}
InsertTabPanel( MediaViewer, 5, Collection.m_Name, Collection.m_UniqueId );
}
else
{
if( MediaViewer )
{
DoPageClose( MediaViewer );
}
}
CollectionsUpdated();
break;
}
case guCOLLECTION_ACTION_VIEW_LIBRARY :
case guCOLLECTION_ACTION_VIEW_ALBUMBROWSER :
case guCOLLECTION_ACTION_VIEW_TREEVIEW :
case guCOLLECTION_ACTION_VIEW_PLAYLISTS :
{
if( MediaViewer )
{
MediaViewer->SetViewMode( ( CollectionCmdId == guCOLLECTION_ACTION_VIEW_LIBRARY ) ? guMEDIAVIEWER_MODE_LIBRARY :
( ( CollectionCmdId - guCOLLECTION_ACTION_VIEW_ALBUMBROWSER ) + 1 ) );
}
else
{
guLogMessage( wxT( "Got a command %i %i %i?" ), CollectionIndex, CollectionCmdId, IsEnabled );
}
break;
}
case guCOLLECTION_ACTION_VIEW_LIB_LABELS :
case guCOLLECTION_ACTION_VIEW_LIB_GENRES :
case guCOLLECTION_ACTION_VIEW_LIB_ARTISTS :
case guCOLLECTION_ACTION_VIEW_LIB_COMPOSERS :
case guCOLLECTION_ACTION_VIEW_LIB_ALBUMARTISTS :
case guCOLLECTION_ACTION_VIEW_LIB_ALBUMS :
case guCOLLECTION_ACTION_VIEW_LIB_YEARS :
case guCOLLECTION_ACTION_VIEW_LIB_RATINGS :
case guCOLLECTION_ACTION_VIEW_LIB_PLAYCOUNT :
{
if( MediaViewer )
{
MediaViewer->ShowPanel( CollectionCmdId, IsEnabled );
}
break;
}
case guCOLLECTION_ACTION_UPDATE_LIBRARY :
case guCOLLECTION_ACTION_RESCAN_LIBRARY :
case guCOLLECTION_ACTION_SEARCH_COVERS :
case guCOLLECTION_ACTION_ADD_PATH :
case guCOLLECTION_ACTION_IMPORT :
{
if( MediaViewer )
{
MediaViewer->HandleCommand( CollectionCmdId );
}
break;
}
case guCOLLECTION_ACTION_VIEW_PROPERTIES :
{
if( MediaViewer )
{
MediaViewer->EditProperties();
}
else if( Collection.m_Type == guMEDIA_COLLECTION_TYPE_NORMAL )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_LIBRARY );
AddPendingEvent( CmdEvent );
}
else if( Collection.m_Type == guMEDIA_COLLECTION_TYPE_JAMENDO )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_JAMENDO );
AddPendingEvent( CmdEvent );
}
else if( Collection.m_Type == guMEDIA_COLLECTION_TYPE_MAGNATUNE )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_MAGNATUNE );
AddPendingEvent( CmdEvent );
}
break;
}
case guCOLLECTION_ACTION_UNMOUNT :
{
if( MediaViewer )
{
MediaViewer->HandleCommand( CollectionCmdId );
}
else
{
guGIO_Mount * Mount = m_VolumeMonitor->GetMountById( Collection.m_UniqueId );
if( Mount && Mount->CanUnmount() )
{
Mount->Unmount();
}
}
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewRadio( wxCommandEvent &event )
{
bool IsEnabled = event.IsChecked();
if( IsEnabled )
{
if( !m_RadioPanel )
m_RadioPanel = new guRadioPanel( m_MainNotebook, m_Db, m_PlayerPanel );
InsertTabPanel( m_RadioPanel, 0, _( "Radio" ), wxT( "Radio" ) );
m_VisiblePanels |= guPANEL_MAIN_RADIOS;
}
else
{
RemoveTabPanel( m_RadioPanel );
m_VisiblePanels ^= guPANEL_MAIN_RADIOS;
}
m_MainNotebook->Refresh();
m_MenuRadios->Check( IsEnabled );
m_MenuRadTextSearch->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_TEXTSEARCH ) );
m_MenuRadTextSearch->Enable( IsEnabled );
// m_MenuRadLabels->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_LABELS ) );
// m_MenuRadLabels->Enable( IsEnabled );
m_MenuRadGenres->Check( m_RadioPanel && m_RadioPanel->IsPanelShown( guPANEL_RADIO_GENRES ) );
m_MenuRadGenres->Enable( IsEnabled );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnRadioShowPanel( wxCommandEvent &event )
{
unsigned int PanelId = 0;
switch( event.GetId() )
{
case ID_MENU_VIEW_RAD_TEXTSEARCH :
PanelId = guPANEL_RADIO_TEXTSEARCH;
m_MenuRadTextSearch->Check( event.IsChecked() );
break;
// case ID_MENU_VIEW_RAD_LABELS :
// PanelId = guPANEL_RADIO_LABELS;
// m_MenuRadLabels->Check( event.IsChecked() );
// break;
case ID_MENU_VIEW_RAD_GENRES :
PanelId = guPANEL_RADIO_GENRES;
m_MenuRadGenres->Check( event.IsChecked() );
break;
}
if( PanelId && m_RadioPanel )
m_RadioPanel->ShowPanel( PanelId, event.IsChecked() );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnRadioProperties( wxCommandEvent &event )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_ONLINE );
AddPendingEvent( CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPodcastsShowPanel( wxCommandEvent &event )
{
unsigned int PanelId = 0;
switch( event.GetId() )
{
case ID_MENU_VIEW_POD_CHANNELS :
PanelId = guPANEL_PODCASTS_CHANNELS;
m_MenuPodChannels->Check( event.IsChecked() );
break;
case ID_MENU_VIEW_POD_DETAILS :
PanelId = guPANEL_PODCASTS_DETAILS;
m_MenuPodDetails->Check( event.IsChecked() );
break;
}
if( PanelId && m_PodcastsPanel )
m_PodcastsPanel->ShowPanel( PanelId, event.IsChecked() );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPodcastsProperties( wxCommandEvent &event )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_PODCASTS );
AddPendingEvent( CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewLastFM( wxCommandEvent &event )
{
bool IsEnabled = event.IsChecked();
if( IsEnabled )
{
if( !m_LastFMPanel )
m_LastFMPanel = new guLastFMPanel( m_MainNotebook, m_Db, m_DbCache, m_PlayerPanel );
InsertTabPanel( m_LastFMPanel, 1, _( "Last.fm" ), wxT( "Last.fm" ) );
m_VisiblePanels |= guPANEL_MAIN_LASTFM;
}
else
{
RemoveTabPanel( m_LastFMPanel );
m_VisiblePanels ^= guPANEL_MAIN_LASTFM;
}
m_MainNotebook->Refresh();
m_MenuLastFM->Check( IsEnabled );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewAudioCD( wxCommandEvent &event )
{
bool IsEnabled = event.IsChecked();
if( IsEnabled )
{
if( !m_AudioCdPanel )
m_AudioCdPanel = new guAudioCdPanel( m_MainNotebook, m_PlayerPanel );
InsertTabPanel( m_AudioCdPanel, 1, _( "Audio CD" ), wxT( "AudioCd" ) );
m_VisiblePanels |= guPANEL_MAIN_AUDIOCD;
}
else
{
RemoveTabPanel( m_AudioCdPanel );
m_VisiblePanels ^= guPANEL_MAIN_AUDIOCD;
}
m_MainNotebook->Refresh();
m_MenuAudioCD->Check( IsEnabled );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewLyrics( wxCommandEvent &event )
{
bool IsEnabled = event.IsChecked();
if( IsEnabled )
{
if( !m_LyricsPanel )
{
m_LyricsPanel = new guLyricsPanel( m_MainNotebook, m_Db, m_LyricSearchEngine );
}
InsertTabPanel( m_LyricsPanel, 2, _( "Lyrics" ), wxT( "Lyrics" ) );
m_VisiblePanels |= guPANEL_MAIN_LYRICS;
}
else
{
RemoveTabPanel( m_LyricsPanel );
m_VisiblePanels ^= guPANEL_MAIN_LYRICS;
}
m_MainNotebook->Refresh();
m_MenuLyrics->Check( IsEnabled );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewPodcasts( wxCommandEvent &event )
{
bool IsEnabled = event.IsChecked();
if( event.IsChecked() )
{
if( !m_PodcastsPanel )
m_PodcastsPanel = new guPodcastPanel( m_MainNotebook, GetPodcastsDb(), this, m_PlayerPanel );
InsertTabPanel( m_PodcastsPanel, 3, _( "Podcasts" ), wxT( "Podcasts" ) );
m_VisiblePanels |= guPANEL_MAIN_PODCASTS;
}
else
{
RemoveTabPanel( m_PodcastsPanel );
m_VisiblePanels ^= guPANEL_MAIN_PODCASTS;
}
m_MainNotebook->Refresh();
m_MenuPodcasts->Check( IsEnabled );
m_MenuPodChannels->Check( m_PodcastsPanel && m_PodcastsPanel->IsPanelShown( guPANEL_PODCASTS_CHANNELS ) );
m_MenuPodChannels->Enable( IsEnabled );
m_MenuPodDetails->Check( m_PodcastsPanel && m_PodcastsPanel->IsPanelShown( guPANEL_PODCASTS_DETAILS ) );
m_MenuPodDetails->Enable( IsEnabled );
m_MenuPodUpdate->Enable( IsEnabled );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewFileBrowser( wxCommandEvent &event )
{
if( event.IsChecked() )
{
if( !m_FileBrowserPanel )
m_FileBrowserPanel = new guFileBrowser( m_MainNotebook, this, m_Db, m_PlayerPanel );
InsertTabPanel( m_FileBrowserPanel, 4, _( "File Browser" ), wxT( "FileBrowser" ) );
m_VisiblePanels |= guPANEL_MAIN_FILEBROWSER;
}
else
{
RemoveTabPanel( m_FileBrowserPanel );
m_VisiblePanels ^= guPANEL_MAIN_FILEBROWSER;
}
m_MainNotebook->Refresh();
m_MenuFileBrowser->Check( m_VisiblePanels & guPANEL_MAIN_FILEBROWSER );
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewPortableDevice( wxCommandEvent &event )
{
int DeviceIndex = event.GetId() - ID_MENU_VIEW_PORTABLE_DEVICE;
guGIO_Mount * Mount = m_VolumeMonitor->GetMount( DeviceIndex );
if( Mount )
{
m_CollectionsMutex.Lock();
guMediaCollection * MediaCollection = new guMediaCollection( guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE );
if( GetPortableMediaType( Mount->GetMountPath() ) == guPORTABLE_MEDIA_TYPE_IPOD )
MediaCollection->m_Type = guMEDIA_COLLECTION_TYPE_IPOD;
MediaCollection->m_Name = Mount->GetName();
MediaCollection->m_UniqueId = Mount->GetId();
MediaCollection->m_Paths.Add( Mount->GetMountPath() );
m_Collections.Add( MediaCollection );
m_CollectionsMutex.Unlock();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->SaveCollections( &m_Collections );
event.SetId( ID_COLLECTIONS_BASE + ( ( m_Collections.Count() - 1 ) * guCOLLECTION_ACTION_COUNT ) );
event.SetInt( 1 );
AddPendingEvent( event );
guLogMessage( wxT( "Sent Event to open collection" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewFullScreen( wxCommandEvent &event )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
bool IsFull = event.IsChecked();
guLogMessage( wxT( "OnViewFullScreen %i" ), IsFull );
if( IsFull )
{
// Save the normal perspective
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_VISIBLE_PANELS, m_VisiblePanels, CONFIG_PATH_MAIN_WINDOW );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( wxT( "PlayerPlayList" ) );
PaneInfo.Caption( _( "Now Playing" ) );
Config->WriteStr( CONFIG_KEY_MAIN_WINDOW_LAST_LAYOUT, m_AuiManager.SavePerspective(), CONFIG_PATH_MAIN_WINDOW );
ShowFullScreen( IsFull, wxFULLSCREEN_NOSTATUSBAR | wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION );
// Restore the previous full screen layout
m_VisiblePanels = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN_VISIBLE_PANELS, guPANEL_MAIN_VISIBLE_DEFAULT, CONFIG_PATH_MAIN_WINDOW_FULLSCREEN );
wxString Perspective = Config->ReadStr( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN_LAST_LAYOUT, wxEmptyString, CONFIG_PATH_MAIN_WINDOW_FULLSCREEN );
LoadPerspective( Perspective );
}
else
{
// Save the full screen layout
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN_VISIBLE_PANELS, m_VisiblePanels, CONFIG_PATH_MAIN_WINDOW_FULLSCREEN );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( wxT( "PlayerPlayList" ) );
PaneInfo.Caption( _( "Now Playing" ) );
Config->WriteStr( CONFIG_KEY_MAIN_WINDOW_FULLSCREEN_LAST_LAYOUT, m_AuiManager.SavePerspective(), CONFIG_PATH_MAIN_WINDOW_FULLSCREEN );
ShowFullScreen( IsFull, wxFULLSCREEN_NOSTATUSBAR | wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION );
// Restore the normal layout
m_VisiblePanels = Config->ReadNum( CONFIG_KEY_MAIN_WINDOW_VISIBLE_PANELS, guPANEL_MAIN_VISIBLE_DEFAULT, CONFIG_PATH_MAIN_WINDOW );
Config->WriteNum( CONFIG_KEY_MAIN_WINDOW_VISIBLE_PANELS, m_VisiblePanels, CONFIG_PATH_MAIN_WINDOW );
wxString Perspective = Config->ReadStr( CONFIG_KEY_MAIN_WINDOW_LAST_LAYOUT, wxEmptyString, CONFIG_PATH_MAIN_WINDOW );
LoadPerspective( Perspective );
}
if( m_MenuFullScreen )
{
m_MenuFullScreen->Check( IsFull );
}
if( m_MPRIS2 )
{
m_MPRIS2->OnFullscreenChanged();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnViewStatusBar( wxCommandEvent &event )
{
m_MainStatusBar->Show( event.IsChecked() );
m_AuiManager.Update();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSetSelection( wxCommandEvent &event )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) event.GetClientData();
if( MediaViewer )
{
int Type = wxNOT_FOUND;
switch( event.GetId() )
{
case ID_MAINFRAME_SELECT_TRACK : Type = guMEDIAVIEWER_SELECT_TRACK; break;
case ID_MAINFRAME_SELECT_ALBUM : Type = guMEDIAVIEWER_SELECT_ALBUM; break;
case ID_MAINFRAME_SELECT_ALBUMARTIST : Type = guMEDIAVIEWER_SELECT_ALBUMARTIST; break;
case ID_MAINFRAME_SELECT_COMPOSER : Type = guMEDIAVIEWER_SELECT_COMPOSER; break;
case ID_MAINFRAME_SELECT_ARTIST : Type = guMEDIAVIEWER_SELECT_ARTIST; break;
case ID_MAINFRAME_SELECT_YEAR : Type = guMEDIAVIEWER_SELECT_YEAR; break;
case ID_MAINFRAME_SELECT_GENRE : Type = guMEDIAVIEWER_SELECT_GENRE; break;
}
if( Type != wxNOT_FOUND )
{
int PanelIndex = m_MainNotebook->GetPageIndex( MediaViewer );
m_MainNotebook->SetSelection( PanelIndex );
MediaViewer->SetSelection( Type, event.GetInt() );
}
}
else if( event.GetExtraLong() == guTRACK_TYPE_PODCAST )
{
int Type = wxNOT_FOUND;
switch( event.GetId() )
{
case ID_MAINFRAME_SELECT_TRACK : Type = guMEDIAVIEWER_SELECT_TRACK; break;
case ID_MAINFRAME_SELECT_ALBUM : Type = guMEDIAVIEWER_SELECT_ALBUM; break;
}
if( Type != wxNOT_FOUND )
{
if( m_PodcastsPanel )
{
int PanelIndex = m_MainNotebook->GetPageIndex( m_PodcastsPanel );
m_MainNotebook->SetSelection( PanelIndex );
m_PodcastsPanel->SetSelection( Type, event.GetInt() );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSelectLocation( wxCommandEvent &event )
{
int PanelIndex = wxNOT_FOUND;
switch( event.GetInt() )
{
case ID_MENU_VIEW_RADIO :
PanelIndex = m_MainNotebook->GetPageIndex( m_RadioPanel );
break;
case ID_MENU_VIEW_LASTFM :
PanelIndex = m_MainNotebook->GetPageIndex( m_LastFMPanel );
break;
case ID_MENU_VIEW_LYRICS :
PanelIndex = m_MainNotebook->GetPageIndex( m_LyricsPanel );
break;
case ID_MENU_VIEW_PODCASTS :
PanelIndex = m_MainNotebook->GetPageIndex( m_PodcastsPanel );
break;
case ID_MENU_VIEW_FILEBROWSER :
PanelIndex = m_MainNotebook->GetPageIndex( m_FileBrowserPanel );
break;
case ID_MENU_VIEW_AUDIOCD :
PanelIndex = m_MainNotebook->GetPageIndex( m_AudioCdPanel );
break;
default : // Its a Collection
{
int CollectionIndex = ( event.GetInt() - ID_COLLECTIONS_BASE ) / guCOLLECTION_ACTION_COUNT;
//int CollectionCmdId = ( event.GetId() - ID_COLLECTIONS_BASE ) % guCOLLECTION_ACTION_COUNT;
guLogMessage( wxT( "Show Location for collection %i" ), CollectionIndex );
guMediaViewer * MediaViewer = FindCollectionMediaViewer( m_Collections[ CollectionIndex ].m_UniqueId );
if( MediaViewer )
{
PanelIndex = m_MainNotebook->GetPageIndex( MediaViewer );
}
break;
}
}
if( PanelIndex != wxNOT_FOUND )
{
m_MainNotebook->SetSelection( PanelIndex );
}
if( m_LocationPanel )
m_LocationPanel->SetFocus();
}
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnGenreSetSelection( wxCommandEvent &event )
//{
// wxArrayInt * genres = ( wxArrayInt * ) event.GetClientData();
// if( genres )
// {
//// m_MainNotebook->SetSelection( 0 );
//// m_LibPanel->SelectGenres( genres );
// delete genres;
// }
//}
//
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnArtistSetSelection( wxCommandEvent &event )
//{
// wxArrayInt * artists = ( wxArrayInt * ) event.GetClientData();
// if( artists )
// {
//// m_MainNotebook->SetSelection( 0 );
//// m_LibPanel->SelectArtists( artists );
// delete artists;
// }
//}
//
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnAlbumArtistSetSelection( wxCommandEvent &event )
//{
// wxArrayInt * Ids = ( wxArrayInt * ) event.GetClientData();
// if( Ids )
// {
//// m_MainNotebook->SetSelection( 0 );
//// m_LibPanel->SelectAlbumArtists( Ids );
// delete Ids;
// }
//}
//
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnComposerSetSelection( wxCommandEvent &event )
//{
// wxArrayInt * Ids = ( wxArrayInt * ) event.GetClientData();
// if( Ids )
// {
//// m_MainNotebook->SetSelection( 0 );
//// m_LibPanel->SelectComposers( Ids );
// delete Ids;
// }
//}
//
//// -------------------------------------------------------------------------------- //
//void guMainFrame::OnAlbumSetSelection( wxCommandEvent &event )
//{
// wxArrayInt * albums = ( wxArrayInt * ) event.GetClientData();
// if( albums )
// {
//// m_MainNotebook->SetSelection( 0 );
//// m_LibPanel->SelectAlbums( albums );
// delete albums;
// }
//}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayListUpdated( wxCommandEvent &event )
{
if( m_PlayerFilters )
m_PlayerFilters->UpdateFilters();
}
// -------------------------------------------------------------------------------- //
int guMainFrame::AddGauge( const wxString &label, const bool showpercent )
{
return m_MainStatusBar->AddGauge( label, showpercent );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::RemoveGauge( const int gaugeid )
{
m_MainStatusBar->RemoveGauge( gaugeid );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnGaugeCreate( wxCommandEvent &event )
{
wxString * Label = ( wxString * ) event.GetClientData();
if( Label )
{
int NewGauge = m_MainStatusBar->AddGauge( * Label, event.GetInt() );
wxEvtHandler * SourceCtrl = ( wxEvtHandler * ) event.GetEventObject();
event.SetId( ID_STATUSBAR_GAUGE_CREATED );
event.SetInt( NewGauge );
event.SetEventObject( this );
wxPostEvent( SourceCtrl, event );
delete Label;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPageChanged( wxAuiNotebookEvent& event )
{
m_CurrentPage = m_MainNotebook->GetPage( m_MainNotebook->GetSelection() );
OnUpdateSelInfo( event );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::DoPageClose( wxPanel * curpage )
{
int PanelId = 0;
if( m_LocationPanel )
m_LocationPanel->Lock();
RemoveTabPanel( curpage );
if( curpage == m_RadioPanel )
{
m_MenuRadios->Check( false );
m_MenuRadTextSearch->Enable( false );
//m_MenuRadLabels->Enable( false );
m_MenuRadGenres->Enable( false );
PanelId = guPANEL_MAIN_RADIOS;
}
else if( curpage == m_LastFMPanel )
{
m_MenuLastFM->Check( false );
PanelId = guPANEL_MAIN_LASTFM;
}
else if( curpage == m_LyricsPanel )
{
m_MenuLyrics->Check( false );
PanelId = guPANEL_MAIN_LYRICS;
}
else if( curpage == m_PodcastsPanel )
{
m_MenuPodcasts->Check( false );
m_MenuPodChannels->Enable( false );
m_MenuPodDetails->Enable( false );
PanelId = guPANEL_MAIN_PODCASTS;
}
else if( curpage == m_FileBrowserPanel )
{
m_MenuFileBrowser->Check( false );
PanelId = guPANEL_MAIN_FILEBROWSER;
}
else if( curpage == m_AudioCdPanel )
{
m_MenuAudioCD->Check( false );
PanelId = guPANEL_MAIN_AUDIOCD;
}
else if( FindCollectionMediaViewer( curpage ) )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) curpage;
MediaViewer->SetMenuState( false );
m_MediaViewers.Remove( MediaViewer );
if( MediaViewer->IsDefault() )
{
guLogMessage( wxT( "Was the default mediaviewer" ) );
MediaViewer->SetViewMode( guMEDIAVIEWER_MODE_NONE );
}
else
{
if( m_MainNotebook->GetPageCount() > 1 )
{
delete MediaViewer;
}
else
{
m_DestroyLastWindow = true;
}
}
CollectionsUpdated();
}
//CheckHideNotebook();
m_VisiblePanels ^= PanelId;
if( m_LocationPanel )
{
m_LocationPanel->OnPanelVisibleChanged();
m_LocationPanel->Unlock();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPageClosed( wxAuiNotebookEvent& event )
{
wxAuiNotebook * ctrl = ( wxAuiNotebook * ) event.GetEventObject();
wxPanel * CurPage = ( wxPanel * ) ctrl->GetPage( event.GetSelection() );
DoPageClose( CurPage );
event.Veto();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnUpdateSelInfo( wxCommandEvent &event )
{
if( !m_CurrentPage )
{
m_MainStatusBar->SetSelInfo( wxEmptyString );
}
else if( m_CurrentPage == ( wxWindow * ) m_RadioPanel )
{
//m_Db->GetRadioCounter( &m_SelCount );
m_RadioPanel->GetRadioCounter( &m_SelCount );
wxString SelInfo = wxString::Format( wxT( "%llu " ), m_SelCount.GetValue() );
SelInfo += m_SelCount == 1 ? _( "station" ) : _( "stations" );
m_MainStatusBar->SetSelInfo( SelInfo );
}
else if( m_CurrentPage == ( wxWindow * ) m_PodcastsPanel )
{
m_PodcastsPanel->GetCounters( &m_SelCount, &m_SelLength, &m_SelSize );
//m_Db->GetPodcastCounters( &m_SelCount, &m_SelLength, &m_SelSize );
wxString SelInfo = wxString::Format( wxT( "%llu " ), m_SelCount.GetValue() );
SelInfo += m_SelCount == 1 ? _( "podcast" ) : _( "podcasts" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( m_SelLength.GetValue() ).c_str(),
SizeToString( m_SelSize.GetValue() ).c_str() );
m_MainStatusBar->SetSelInfo( SelInfo );
}
else if( m_CurrentPage == ( wxWindow * ) m_LyricsPanel )
{
m_MainStatusBar->SetSelInfo( m_LyricsPanel->GetLyricSource() );
}
else if( m_CurrentPage == ( wxWindow * ) m_FileBrowserPanel )
{
if( m_FileBrowserPanel->GetCounters( &m_SelCount, &m_SelLength, &m_SelSize ) )
{
wxString SelInfo = wxString::Format( wxT( "%llu " ), m_SelLength.GetValue() );
SelInfo += m_SelLength == 1 ? _( "dir" ) : _( "dirs" );
SelInfo += wxString::Format( wxT( ", %llu " ), m_SelCount.GetValue() );
SelInfo += m_SelLength == 1 ? _( "file" ) : _( "files" );
SelInfo += wxString::Format( wxT( ", %s" ),
SizeToString( m_SelSize.GetValue() ).c_str() );
m_MainStatusBar->SetSelInfo( SelInfo );
}
else
{
m_MainStatusBar->SetSelInfo( wxEmptyString );
}
}
else if( m_CurrentPage == ( wxWindow * ) m_AudioCdPanel )
{
m_AudioCdPanel->GetCounters( &m_SelCount, &m_SelLength, &m_SelSize );
wxString SelInfo = wxString::Format( wxT( "%llu " ), m_SelCount.GetValue() );
SelInfo += m_SelCount == 1 ? _( "track" ) : _( "tracks" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( m_SelLength.GetValue() ).c_str(),
SizeToString( m_SelSize.GetValue() ).c_str() );
m_MainStatusBar->SetSelInfo( SelInfo );
}
else
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) FindCollectionMediaViewer( m_CurrentPage );
if( MediaViewer )
{
m_MainStatusBar->SetSelInfo( MediaViewer->GetSelInfo() );
}
else
{
//m_SelCount = wxNOT_FOUND;
//m_SelLength = wxNOT_FOUND;
//m_SelSize = wxNOT_FOUND;
m_MainStatusBar->SetSelInfo( wxEmptyString );
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnRequestCurrentTrack( wxCommandEvent &event )
{
const guCurrentTrack * CurrentTrack = m_PlayerPanel->GetCurrentTrack();
if( CurrentTrack->m_Loaded )
{
wxCommandEvent UpdateEvent( wxEVT_MENU, ID_PLAYERPANEL_TRACKCHANGED );
guTrack * Track = new guTrack( * CurrentTrack );
UpdateEvent.SetClientData( Track );
if( event.GetClientData() == m_LyricsPanel )
{
m_LyricsPanel->OnSetCurrentTrack( UpdateEvent );
if( m_LyricSearchEngine )
{
if( m_LyricSearchContext )
delete m_LyricSearchContext;
m_LyricSearchContext = m_LyricSearchEngine->CreateContext( this, Track );
m_LyricSearchEngine->SearchStart( m_LyricSearchContext );
}
}
else if( event.GetClientData() == m_LastFMPanel )
{
m_LastFMPanel->OnUpdatedTrack( UpdateEvent );
}
delete Track;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnIdle( wxIdleEvent& WXUNUSED( event ) )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Unbind( wxEVT_IDLE, &guMainFrame::OnIdle, this );
m_MainStatusBar->Show( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_STATUS_BAR, true, CONFIG_PATH_MAIN_WINDOW ) );
// If the Podcasts update is enable launch it...
if( Config->ReadBool( CONFIG_KEY_PODCASTS_UPDATE, true, CONFIG_PATH_PODCASTS ) )
{
guLogMessage( wxT( "Updating the podcasts..." ) );
wxCommandEvent event( wxEVT_MENU, ID_MENU_UPDATE_PODCASTS );
AddPendingEvent( event );
}
// Add the previously pending podcasts to download
guDbPodcasts * DbPodcasts = GetPodcastsDb();
guPodcastItemArray Podcasts;
DbPodcasts->GetPendingPodcasts( &Podcasts );
if( Podcasts.Count() )
AddPodcastsDownloadItems( &Podcasts );
// Now we can start the dbus server
m_DBusServer->Run();
CreateTaskBarIcon();
if( m_PlayerPlayList )
{
m_PlayerPlayList->LoadPlaylistTracks();
}
if( m_PlayerPanel )
{
if( m_PlayerPanel->GetAudioScrobbleEnabled() )
{
wxCommandEvent Event;
OnAudioScrobbleUpdate( Event );
}
m_PlayerPanel->CheckStartPlaying();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateTaskBarIcon( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
bool ShowIcon = Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_TASK_BAR_ICON, true, CONFIG_PATH_GENERAL );
bool SoundMenuEnabled = false;
if( ShowIcon )
{
if( m_MPRIS2->Indicators_Sound_Available() )
{
SoundMenuEnabled = Config->ReadBool( CONFIG_KEY_GENERAL_SOUND_MENU_INTEGRATE, false, CONFIG_PATH_GENERAL );
int IsBlacklisted = m_MPRIS2->Indicators_Sound_IsBlackListed();
if( IsBlacklisted != wxNOT_FOUND )
{
if( SoundMenuEnabled == bool( IsBlacklisted ) )
{
m_MPRIS2->Indicators_Sound_BlacklistMediaPlayer( !SoundMenuEnabled );
}
}
}
if( SoundMenuEnabled )
{
if( m_TaskBarIcon )
{
m_TaskBarIcon->RemoveIcon();
delete m_TaskBarIcon;
m_TaskBarIcon = NULL;
}
}
else
{
if( m_MPRIS2->Indicators_Sound_Available() )
{
int IsBlacklisted = m_MPRIS2->Indicators_Sound_IsBlackListed();
if( IsBlacklisted != wxNOT_FOUND )
{
if( !IsBlacklisted )
{
m_MPRIS2->Indicators_Sound_BlacklistMediaPlayer( true );
}
}
}
if( !m_TaskBarIcon )
{
m_TaskBarIcon = new guTaskBarIcon( this, m_PlayerPanel );
if( m_TaskBarIcon )
{
m_TaskBarIcon->SetIcon( m_AppIcon, wxT( "Guayadeque Music Player " ID_GUAYADEQUE_VERSION "-" ID_GUAYADEQUE_REVISION ) );
}
}
}
}
else
{
if( m_MPRIS2->Indicators_Sound_Available() )
{
int IsBlacklisted = m_MPRIS2->Indicators_Sound_IsBlackListed();
if( IsBlacklisted != wxNOT_FOUND )
{
if( !IsBlacklisted )
{
m_MPRIS2->Indicators_Sound_BlacklistMediaPlayer( true );
}
}
}
if( m_TaskBarIcon )
{
m_TaskBarIcon->RemoveIcon();
delete m_TaskBarIcon;
m_TaskBarIcon = NULL;
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::UpdatePodcasts( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_PODCASTS_UPDATE, true, CONFIG_PATH_PODCASTS ) )
{
if( !m_UpdatePodcastsTimer )
{
//guLogMessage( wxT( "Creating the UpdatePodcasts timer..." ) );
m_UpdatePodcastsTimer = new guUpdatePodcastsTimer( this, m_Db );
m_UpdatePodcastsTimer->Start( guPODCASTS_UPDATE_TIMEOUT );
}
wxDateTime LastUpdate;
LastUpdate.ParseDateTime( Config->ReadStr( CONFIG_KEY_PODCASTS_LASTUPDATE,
wxDateTime::Now().Format(),
CONFIG_PATH_PODCASTS ) );
if( !LastUpdate.IsValid() )
LastUpdate = wxDateTime::Now();
wxDateTime UpdateTime = wxDateTime::Now();
switch( Config->ReadNum( CONFIG_KEY_PODCASTS_UPDATEPERIOD,
guPODCAST_UPDATE_HOUR,
CONFIG_PATH_PODCASTS ) )
{
case guPODCAST_UPDATE_HOUR : // Hour
UpdateTime.Subtract( wxTimeSpan::Hour() );
break;
case guPODCAST_UPDATE_DAY : // Day
UpdateTime.Subtract( wxDateSpan::Day() );
break;
case guPODCAST_UPDATE_WEEK : // Week
UpdateTime.Subtract( wxDateSpan::Week() );
break;
case guPODCAST_UPDATE_MONTH : // Month
UpdateTime.Subtract( wxDateSpan::Month() );
break;
default :
guLogError( wxT( "Unrecognized UpdatePeriod in podcasts" ) );
return;
}
//guLogMessage( wxT( "%s -- %s" ), LastUpdate.Format().c_str(), UpdateTime.Format().c_str() );
if( UpdateTime.IsLaterThan( LastUpdate ) )
{
//guLogMessage( wxT( "Starting UpdatePodcastsThread Process..." ) );
int GaugeId = m_MainStatusBar->AddGauge( _( "Podcasts" ) );
guUpdatePodcastsThread * UpdatePodcastThread = new guUpdatePodcastsThread( this, GaugeId );
if( !UpdatePodcastThread )
{
guLogError( wxT( "Could not create the Update Podcasts thread" ) );
}
Config->WriteStr( CONFIG_KEY_PODCASTS_LASTUPDATE,
wxDateTime::Now().Format(),
CONFIG_PATH_PODCASTS );
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::AddPodcastsDownloadItems( guPodcastItemArray * items )
{
int Count = items->Count();
if( Count )
{
if( !m_DownloadThread )
{
m_DownloadThread = new guPodcastDownloadQueueThread( this );
}
guDbPodcasts * DbPodcasts = GetPodcastsDb();
for( int Index = 0; Index < Count; Index++ )
{
if( items->Item( Index ).m_Status != guPODCAST_STATUS_PENDING )
{
items->Item( Index ).m_Status = guPODCAST_STATUS_PENDING;
DbPodcasts->SetPodcastItemStatus( items->Item( Index ).m_Id, guPODCAST_STATUS_PENDING );
}
}
m_DownloadThread->AddPodcastItems( items );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::RemovePodcastDownloadItems( guPodcastItemArray * items )
{
if( m_DownloadThread )
{
m_DownloadThread->RemovePodcastItems( items );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnRemovePodcastThread( wxCommandEvent &event )
{
RemovePodcastsDownloadThread();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::RemovePodcastsDownloadThread( void )
{
wxMutexLocker Lock( m_DownloadThreadMutex );
if( m_DownloadThread && !m_DownloadThread->GetCount() )
{
m_DownloadThread->Pause();
m_DownloadThread->Delete();
//guLogMessage( wxT( "Podcast Download Thread destroyed..." ) );
m_DownloadThread = NULL;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPodcastItemUpdated( wxCommandEvent &event )
{
if( m_PodcastsPanel )
{
wxPostEvent( m_PodcastsPanel, event );
}
else
{
guPodcastItem * PodcastItem = ( guPodcastItem * ) event.GetClientData();
delete PodcastItem;
}
}
// -------------------------------------------------------------------------------- //
wxString GetLayoutName( const wxString &filename )
{
wxString LayoutName;
//guLogMessage( wxT( "Layout file: '%s'" ), filename.c_str() );
wxFileInputStream Ins( filename );
if( Ins.IsOk() )
{
wxXmlDocument XmlDoc( Ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "layout" ) )
{
XmlNode->GetAttribute( wxT( "name" ), &LayoutName );
}
}
return LayoutName;
}
// -------------------------------------------------------------------------------- //
wxString GetLayoutFileName( const wxString &layoutname )
{
wxRegEx ReplaceEx( wxT( "[ <>:\\\\|\\?\\*]" ) );
wxString LayoutName = layoutname;
ReplaceEx.Replace( &LayoutName, wxT( "_" ) );
LayoutName = guPATH_LAYOUTS + LayoutName + wxT( ".xml" );
return LayoutName;
}
// -------------------------------------------------------------------------------- //
void guMainFrame::LoadLayoutNames( void )
{
m_LayoutNames.Empty();
wxDir Dir;
wxString FileName;
wxString LayoutDir = guPATH_LAYOUTS;
Dir.Open( LayoutDir );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES ) )
{
do {
if( FileName[ 0 ] == '.' )
continue;
if( FileName.EndsWith( wxT( ".xml" ) ) )
{
wxString LayoutName = GetLayoutName( LayoutDir + FileName );
//guLogMessage( wxT( "LayoutName: '%s'" ), LayoutName.c_str() );
if( !LayoutName.IsEmpty() )
{
m_LayoutNames.Add( LayoutName );
}
}
} while( Dir.GetNext( &FileName ) );
m_LayoutNames.Sort();
}
}
else
{
guLogMessage( wxT( "Could not open the Layouts dir" ) );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::ReloadLayoutMenus( void )
{
LoadLayoutNames();
while( m_MenuLayoutLoad->GetMenuItemCount() )
m_MenuLayoutLoad->Destroy( m_MenuLayoutLoad->FindItemByPosition( 0 ) );
while( m_MenuLayoutDelete->GetMenuItemCount() )
m_MenuLayoutDelete->Destroy( m_MenuLayoutDelete->FindItemByPosition( 0 ) );
int Count = m_LayoutNames.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
m_MenuLayoutLoad->Append( ID_MENU_LAYOUT_LOAD + Index, m_LayoutNames[ Index ], _( "Load this user defined layout" ) );
m_MenuLayoutDelete->Append( ID_MENU_LAYOUT_DELETE + Index, m_LayoutNames[ Index ], _( "Delete this user defined layout" ) );
}
}
else
{
wxMenuItem * MenuItem = new wxMenuItem( m_MenuLayoutLoad, ID_MENU_LAYOUT_DUMMY, _( "No Layouts Defined" ), _( "Load this user defined layout" ) );
m_MenuLayoutLoad->Append( MenuItem );
MenuItem->Enable( false );
MenuItem = new wxMenuItem( m_MenuLayoutLoad, ID_MENU_LAYOUT_DUMMY, _( "No Layouts Defined" ), _( "Load this user defined layout" ) );
m_MenuLayoutDelete->Append( MenuItem );
MenuItem->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
bool guMainFrame::SaveCurrentLayout( const wxString &layoutname )
{
wxXmlNode * RootNode;
wxXmlNode * XmlNode;
wxXmlDocument OutXml;
// RootNode
//
RootNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "layout" ) );
wxXmlAttribute * Property = new wxXmlAttribute( wxT( "name" ), layoutname,
new wxXmlAttribute( wxT( "version" ), wxT( "1.0" ),
NULL ) );
RootNode->SetAttributes( Property );
// MainWindow
//
XmlNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "mainwindow" ) );
// Size
int Width;
int Height;
GetSize( &Width, &Height );
// Pos
int PosX;
int PosY;
GetPosition( &PosX, &PosY );
// State
int State = guWINDOW_STATE_NORMAL;
if( IsFullScreen() )
State |= guWINDOW_STATE_FULLSCREEN;
if( IsMaximized() )
State |= guWINDOW_STATE_MAXIMIZED;
if( !m_MainStatusBar->IsShown() )
State |= guWINDOW_STATE_NOSTATUSBAR;
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( wxT( "PlayerPlayList" ) );
wxString PLCaption = PaneInfo.caption;
PaneInfo.Caption( wxT( "Now Playing" ) );
Property = new wxXmlAttribute( wxT( "posx" ), wxString::Format( wxT( "%d" ), PosX ),
new wxXmlAttribute( wxT( "posy" ), wxString::Format( wxT( "%d" ), PosY ),
new wxXmlAttribute( wxT( "width" ), wxString::Format( wxT( "%d" ), Width ),
new wxXmlAttribute( wxT( "height" ), wxString::Format( wxT( "%d" ), Height ),
new wxXmlAttribute( wxT( "state" ), wxString::Format( wxT( "%d" ), State ),
new wxXmlAttribute( wxT( "panels" ), wxString::Format( wxT( "%d" ), m_VisiblePanels ),
new wxXmlAttribute( wxT( "layout" ), m_AuiManager.SavePerspective(),
new wxXmlAttribute( wxT( "tabslayout" ), m_MainNotebook->SavePerspective(),
NULL ) ) ) ) ) ) ) );
XmlNode->SetAttributes( Property );
RootNode->AddChild( XmlNode );
// Radio
//
if( m_RadioPanel )
{
m_RadioPanel->SaveLayout( RootNode, wxT( "radio" ) );
}
// Podcasts
//
if( m_PodcastsPanel )
{
m_PodcastsPanel->SaveLayout( RootNode, wxT( "podcasts" ) );
}
// FileBrowser
//
if( m_FileBrowserPanel )
{
m_FileBrowserPanel->SaveLayout( RootNode, wxT( "filebrowser" ) );
}
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_MediaViewers[ Index ]->SaveLayout( RootNode );
}
OutXml.SetRoot( RootNode );
return OutXml.Save( GetLayoutFileName( layoutname ) );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnCreateNewLayout( wxCommandEvent &event )
{
// wxTextEntryDialog EntryDialog( this, _( "Enter the layout name:"), _( "New Layout" ) );
guEditWithOptions * SaveLayoutDialog = new guEditWithOptions( this, _( "Save Layout" ),
_( "Layout:" ), wxString::Format( _( "Layout %lu" ), m_LayoutNames.GetCount() + 1 ), m_LayoutNames );
if( SaveLayoutDialog )
{
if( SaveLayoutDialog->ShowModal() == wxID_OK )
{
if( !SaveCurrentLayout( SaveLayoutDialog->GetData() ) )
{
guLogMessage( wxT( "Could not save the layout '%s'" ), SaveLayoutDialog->GetData().c_str() );
}
else
{
ReloadLayoutMenus();
}
}
SaveLayoutDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnDeleteLayout( wxCommandEvent &event )
{
int Layout = event.GetId() - ID_MENU_LAYOUT_DELETE;
//guLogMessage( wxT( "Delete Layout %i" ), Layout );
if( Layout >= 0 && Layout < ( int ) m_LayoutNames.Count() )
{
wxString LayoutFile = GetLayoutFileName( m_LayoutNames[ Layout ] );
if( wxFileExists( LayoutFile ) )
{
wxRemoveFile( LayoutFile );
ReloadLayoutMenus();
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::LoadPerspective( const wxString &layout )
{
m_AuiManager.LoadPerspective( layout, true );
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( m_MainNotebook );
if( !PaneInfo.IsShown() )
{
m_VisiblePanels = m_VisiblePanels & ( guPANEL_MAIN_PLAYERPLAYLIST |
guPANEL_MAIN_PLAYERFILTERS |
guPANEL_MAIN_PLAYERVUMETERS |
guPANEL_MAIN_LOCATIONS |
guPANEL_MAIN_SHOWCOVER );
// Reset the Menu entry for all elements
// ResetViewMenuState();
}
//m_AuiManager.Update();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSize( wxSizeEvent &event )
{
wxSize Size = event.GetSize();
guLogMessage( wxT( "MainFrame.Size( %i, %i ) %i" ), Size.GetWidth(), Size.GetHeight(), m_LoadLayoutPending );
if( m_LoadLayoutPending != wxNOT_FOUND )
{
//guLogMessage( wxT( "LoadLayout command sent" ) );
wxCommandEvent LoadLayoutEvent( wxEVT_MENU, ID_MENU_LAYOUT_LOAD + m_LoadLayoutPending );
m_LoadLayoutPending = wxNOT_FOUND;
AddPendingEvent( LoadLayoutEvent );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnIconize( wxIconizeEvent &event )
{
guLogMessage( wxT( "MainFrame::OnIconize: %i" ), event.IsIconized() );
if( !event.IsIconized() )
{
Layout();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLoadLayout( wxCommandEvent &event )
{
int LayoutIndex = event.GetId() - ID_MENU_LAYOUT_LOAD;
//guLogMessage( wxT( "Loading LayoutIndex %i" ), LayoutIndex );
if( LayoutIndex >= 0 && LayoutIndex < ( int ) m_LayoutNames.Count() )
{
wxString LayoutFile = GetLayoutFileName( m_LayoutNames[ LayoutIndex ] );
if( wxFileExists( LayoutFile ) )
{
wxFileInputStream Ins( LayoutFile );
if( Ins.IsOk() )
{
wxXmlDocument XmlDoc( Ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "layout" ) )
{
wxArrayString OpenViewers;
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
guMediaViewer * CurMediaViewer = m_MediaViewers[ Index ];
if( !CurMediaViewer->IsDefault() ||
CurMediaViewer->GetViewMode() != guMEDIAVIEWER_MODE_NONE )
{
OpenViewers.Add( CurMediaViewer->GetMediaCollection()->m_UniqueId );
}
}
Hide();
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
wxString NodeName = XmlNode->GetName();
if( NodeName == wxT( "mainwindow" ) )
{
wxString Field;
long PosX;
long PosY;
long Width;
long Height;
long State;
long VisiblePanels;
wxString LayoutStr;
wxString TabsLayoutStr;
XmlNode->GetAttribute( wxT( "posx" ), &Field );
Field.ToLong( &PosX );
XmlNode->GetAttribute( wxT( "posy" ), &Field );
Field.ToLong( &PosY );
XmlNode->GetAttribute( wxT( "width" ), &Field );
Field.ToLong( &Width );
XmlNode->GetAttribute( wxT( "height" ), &Field );
Field.ToLong( &Height );
XmlNode->GetAttribute( wxT( "state" ), &Field );
Field.ToLong( &State );
XmlNode->GetAttribute( wxT( "panels" ), &Field );
Field.ToLong( &VisiblePanels );
XmlNode->GetAttribute( wxT( "layout" ), &LayoutStr );
XmlNode->GetAttribute( wxT( "tabslayout" ), &TabsLayoutStr );
if( IsFullScreen() != bool( State & guWINDOW_STATE_FULLSCREEN ) )
{
ShowFullScreen( bool( State & guWINDOW_STATE_FULLSCREEN ), wxFULLSCREEN_NOSTATUSBAR | wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION );
if( bool( State & guWINDOW_STATE_FULLSCREEN ) )
Hide();
m_LoadLayoutPending = LayoutIndex;
Refresh();
Update();
m_MenuFullScreen->Check( bool( State & guWINDOW_STATE_FULLSCREEN ) );
}
if( IsMaximized() != bool( State & guWINDOW_STATE_MAXIMIZED ) )
{
Maximize( bool( State & guWINDOW_STATE_MAXIMIZED ) );
m_LoadLayoutPending = LayoutIndex;
Refresh();
Update();
}
if( !m_MainStatusBar->IsShown() != bool( State & guWINDOW_STATE_NOSTATUSBAR ) )
{
m_MainStatusBar->Show( !( State & guWINDOW_STATE_NOSTATUSBAR ) );
Refresh();
Update();
m_MenuStatusBar->Check( !( State & guWINDOW_STATE_NOSTATUSBAR ) );
}
if( !( State & ( guWINDOW_STATE_MAXIMIZED | guWINDOW_STATE_FULLSCREEN ) ) )
{
SetSize( PosX, PosY, Width, Height );
Refresh();
Update();
}
LoadTabsPerspective( TabsLayoutStr );
wxArrayInt PanelIds;
PanelIds.Add( guPANEL_MAIN_PLAYERPLAYLIST );
PanelIds.Add( guPANEL_MAIN_PLAYERFILTERS );
PanelIds.Add( guPANEL_MAIN_PLAYERVUMETERS );
PanelIds.Add( guPANEL_MAIN_LOCATIONS );
PanelIds.Add( guPANEL_MAIN_SHOWCOVER );
int Count = PanelIds.Count();
for( int Index = 0; Index < Count; Index++ )
{
int PanelId = PanelIds[ Index ];
if( ( VisiblePanels & PanelId ) != ( int ) ( m_VisiblePanels & PanelId ) )
{
ShowMainPanel( PanelId, ( VisiblePanels & PanelId ) );
}
}
LoadPerspective( LayoutStr );
OnPlayerPlayListUpdateTitle( event );
}
else if( NodeName == wxT( "radio" ) )
{
if( m_RadioPanel )
{
m_RadioPanel->LoadLayout( XmlNode );
}
}
else if( NodeName == wxT( "podcasts" ) )
{
if( m_PodcastsPanel )
{
m_PodcastsPanel->LoadLayout( XmlNode );
}
}
else if( NodeName == wxT( "filebrowser" ) )
{
if( m_FileBrowserPanel )
{
m_FileBrowserPanel->LoadLayout( XmlNode );
}
}
else if( NodeName == wxT( "mediaviewer" ) )
{
wxString UniqueId;
XmlNode->GetAttribute( wxT( "id" ), &UniqueId );
int CollectionIndex = FindCollectionUniqueId( &m_Collections, UniqueId );
if( CollectionIndex != wxNOT_FOUND )
{
guMediaCollection &Collection = m_Collections[ CollectionIndex ];
if( OpenViewers.Index( UniqueId ) != wxNOT_FOUND )
{
OpenViewers.Remove( UniqueId );
}
guMediaViewer * MediaViewer = FindCollectionMediaViewer( UniqueId );
if( !MediaViewer ||
( MediaViewer->IsDefault() && ( MediaViewer->GetViewMode() == guMEDIAVIEWER_MODE_NONE ) ) ||
( ( ( Collection.m_Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( Collection.m_Type == guMEDIA_COLLECTION_TYPE_IPOD ) ) &&
IsCollectionActive( Collection.m_UniqueId ) ) )
{
event.SetId( ID_COLLECTIONS_BASE + ( CollectionIndex * guCOLLECTION_ACTION_COUNT ) );
event.SetInt( 1 );
OnCollectionCommand( event );
}
while( !MediaViewer )
{
MediaViewer = FindCollectionMediaViewer( UniqueId );
wxMilliSleep( 5 );
}
MediaViewer->LoadLayout( XmlNode );
}
}
XmlNode = XmlNode->GetNext();
}
if( OpenViewers.Count() )
{
Count = OpenViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
int CollectionIndex = FindCollectionUniqueId( &m_Collections, OpenViewers[ Index ] );
event.SetId( ID_COLLECTIONS_BASE + ( CollectionIndex * guCOLLECTION_ACTION_COUNT ) );
event.SetInt( 0 );
OnCollectionCommand( event );
}
}
// RefreshViewMenuState();
Show();
}
}
else
{
guLogError( wxT( "Could not read the file '%s'" ), LayoutFile.c_str() );
}
}
else
{
guLogError( wxT( "Could not find the file '%s'" ), LayoutFile.c_str() );
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::LoadTabsPerspective( const wxString &layout )
{
wxCommandEvent event;
if( m_LocationPanel )
m_LocationPanel->Lock();
// Empty the tabs
int Count = m_MainNotebook->GetPageCount();
for( int Index = 0; Index < Count; Index++ )
{
RemoveTabPanel( ( wxPanel * ) m_MainNotebook->GetPage( 0 ) );
}
// Add the tabs in the proper ordering
wxString TabsLayout = layout.AfterFirst( wxT( '=' ) );
TabsLayout = TabsLayout.BeforeFirst( wxT( '@' ) );
event.SetInt( 1 );
m_VisiblePanels = m_VisiblePanels & ( guPANEL_MAIN_PLAYERPLAYLIST |
guPANEL_MAIN_PLAYERFILTERS |
guPANEL_MAIN_PLAYERVUMETERS |
guPANEL_MAIN_LOCATIONS |
guPANEL_MAIN_SHOWCOVER );
// Reset the Menu entry for all elements
// ResetViewMenuState();
int Index = 0;
while( true )
{
int FindPos = TabsLayout.Find( wxString::Format( wxT( "%02i[" ), Index ) );
if( FindPos == wxNOT_FOUND )
break;
wxString TabName = TabsLayout.Mid( FindPos ).AfterFirst( wxT( '[' ) ).BeforeFirst( wxT( ']' ) );
//guLogMessage( wxT( "Creating tab %i '%s'" ), Index, TabName.c_str() );
if( TabName == wxT( "Radio" ) )
{
OnViewRadio( event );
}
else if( TabName == wxT( "Last.fm" ) )
{
OnViewLastFM( event );
}
else if( TabName == wxT( "AudioCd" ) )
{
OnViewAudioCD( event );
}
else if( TabName == wxT( "Lyrics" ) )
{
OnViewLyrics( event );
}
else if( TabName == wxT( "Podcasts" ) )
{
OnViewPodcasts( event );
}
else if( TabName == wxT( "FileBrowser" ) )
{
OnViewFileBrowser( event );
}
else // It must be a collection
{
//guMediaViewer * MediaViewer = FindCollectionMediaViewer( TabName );
int CollectionIndex = FindCollectionUniqueId( &m_Collections, TabName );
if( CollectionIndex != wxNOT_FOUND )
{
if( m_Collections[ CollectionIndex ].m_Type < guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE )
{
event.SetId( ID_COLLECTIONS_BASE + ( CollectionIndex * guCOLLECTION_ACTION_COUNT ) );
event.SetInt( 1 );
OnCollectionCommand( event );
}
}
}
Index++;
}
m_MainNotebook->LoadPerspective( layout );
if( m_LocationPanel )
m_LocationPanel->Unlock();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnMainPaneClose( wxAuiManagerEvent &event )
{
wxAuiPaneInfo * PaneInfo = event.GetPane();
wxString PaneName = PaneInfo->name;
int CmdId = 0;
if( PaneName == wxT( "PlayerPlayList" ) )
{
CmdId = ID_MENU_VIEW_PLAYER_PLAYLIST;
}
else if( PaneName == wxT( "PlayerFilters" ) )
{
CmdId = ID_MENU_VIEW_PLAYER_FILTERS;
}
else if( PaneName == wxT( "PlayerVumeters" ) )
{
CmdId = ID_MENU_VIEW_PLAYER_VUMETERS;
}
else if( PaneName == wxT( "PlayerSelector" ) )
{
CmdId = ID_MENU_VIEW_PLAYER_NOTEBOOK;
}
else if( PaneName == wxT( "MainSources" ) )
{
CmdId = ID_MENU_VIEW_MAIN_LOCATIONS;
}
else if( PaneName == wxT( "MainShowCover" ) )
{
CmdId = ID_MENU_VIEW_MAIN_SHOWCOVER;
}
//guLogMessage( wxT( "OnMainPaneClose: %s %i" ), PaneName.c_str(), CmdId );
if( CmdId )
{
wxCommandEvent evt( wxEVT_MENU, CmdId );
evt.SetInt( 0 );
AddPendingEvent( evt );
}
event.Veto();
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerShowPanel( wxCommandEvent &event )
{
unsigned int PanelId = 0;
switch( event.GetId() )
{
case ID_MENU_VIEW_PLAYER_PLAYLIST :
{
PanelId = guPANEL_MAIN_PLAYERPLAYLIST;
break;
}
case ID_MENU_VIEW_PLAYER_FILTERS :
{
PanelId = guPANEL_MAIN_PLAYERFILTERS;
break;
}
case ID_MENU_VIEW_PLAYER_VUMETERS :
{
PanelId = guPANEL_MAIN_PLAYERVUMETERS;
break;
}
case ID_MENU_VIEW_PLAYER_NOTEBOOK :
{
if( m_VisiblePanels & guPANEL_MAIN_RADIOS )
OnViewRadio( event );
if( m_VisiblePanels & guPANEL_MAIN_LASTFM )
OnViewLastFM( event );
if( m_VisiblePanels & guPANEL_MAIN_LYRICS )
OnViewLyrics( event );
if( m_VisiblePanels & guPANEL_MAIN_PODCASTS )
OnViewPodcasts( event );
if( m_VisiblePanels & guPANEL_MAIN_FILEBROWSER )
OnViewFileBrowser( event );
break;
}
case ID_MENU_VIEW_MAIN_LOCATIONS :
{
PanelId = guPANEL_MAIN_LOCATIONS;
break;
}
case ID_MENU_VIEW_MAIN_SHOWCOVER :
{
PanelId = guPANEL_MAIN_SHOWCOVER;
break;
}
default :
return;
}
if( PanelId )
ShowMainPanel( PanelId, event.IsChecked() );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::ShowMainPanel( const int panelid, const bool show )
{
//guLogMessage( wxT( "ShowMainPanel( %08X, %i )" ), panelid, show );
wxString PaneName;
switch( panelid )
{
case guPANEL_MAIN_PLAYERPLAYLIST :
PaneName = wxT( "PlayerPlayList" );
m_MenuPlayerPlayList->Check( show );
break;
case guPANEL_MAIN_PLAYERFILTERS :
PaneName = wxT( "PlayerFilters" );
m_MenuPlayerFilters->Check( show );
break;
case guPANEL_MAIN_PLAYERVUMETERS :
if( !m_PlayerVumeters )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_PlayerVumeters = new guPlayerVumeters( this );
m_AuiManager.AddPane( m_PlayerVumeters, wxAuiPaneInfo().Name( wxT( "PlayerVumeters" ) ).Caption( _( "VU Meters" ) ).
DestroyOnClose( false ).Resizable( true ).Floatable( true ).MinSize( 50, 50 ).
CloseButton( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL ) ).
Left().Layer( 0 ).Row( 1 ).Position( 1 ).Hide() );
if( m_PlayerPanel )
m_PlayerPanel->SetPlayerVumeters( m_PlayerVumeters );
}
PaneName = wxT( "PlayerVumeters" );
if( m_MenuPlayerVumeters )
m_MenuPlayerVumeters->Check( show );
break;
case guPANEL_MAIN_LOCATIONS :
if( !m_LocationPanel )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_LocationPanel = new guLocationPanel( this );
m_AuiManager.AddPane( m_LocationPanel, wxAuiPaneInfo().Name( wxT( "MainSources" ) ).Caption( _( "Sources" ) ).
DestroyOnClose( false ).Resizable( true ).Floatable( true ).MinSize( 20, 20 ).
CloseButton( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL ) ).
Left().Layer( 3 ).Row( 0 ).Position( 0 ).Hide() );
}
PaneName = wxT( "MainSources" );
if( m_MenuMainLocations )
m_MenuMainLocations->Check( show );
break;
case guPANEL_MAIN_SHOWCOVER :
if( !m_CoverPanel )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_CoverPanel = new guCoverPanel( this, m_PlayerPanel );
m_AuiManager.AddPane( m_CoverPanel, wxAuiPaneInfo().Name( wxT( "MainShowCover" ) ).Caption( _( "Cover" ) ).
DestroyOnClose( false ).Resizable( true ).Floatable( true ).MinSize( 50, 50 ).
CloseButton( Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL ) ).
Left().Layer( 3 ).Row( 0 ).Position( 0 ).Hide() );
}
PaneName = wxT( "MainShowCover" );
if( m_MenuMainShowCover )
m_MenuMainShowCover->Check( show );
break;
default :
return;
}
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( PaneName );
if( PaneInfo.IsOk() )
{
if( show )
{
PaneInfo.Show();
guConfig * Config = ( guConfig * ) guConfig::Get();
DoShowCaptions( Config->ReadBool( CONFIG_KEY_MAIN_WINDOW_CAPTIONS, true, CONFIG_PATH_MAIN_WINDOW ) );
}
else
{
PaneInfo.Hide();
}
m_AuiManager.Update();
}
if( show )
m_VisiblePanels |= panelid;
else
m_VisiblePanels ^= panelid;
//guLogMessage( wxT( "Id: %i Pane: %s Show:%i Flags:%08X" ), panelid, PaneName.c_str(), show, m_VisiblePanels );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::UpdatedTracks( int updatedby, const guTrackArray * tracks )
{
if( !tracks->Count() )
return;
if( updatedby != guUPDATED_TRACKS_PLAYER )
{
m_PlayerPanel->UpdatedTracks( tracks );
}
if( updatedby != guUPDATED_TRACKS_PLAYER_PLAYLIST )
{
m_PlayerPlayList->UpdatedTracks( tracks );
}
if( updatedby != guUPDATED_TRACKS_MEDIAVIEWER )
{
int Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_MediaViewers[ Index ]->UpdatedTracks( updatedby, tracks );
}
}
if( m_LyricsPanel )
{
m_LyricsPanel->UpdatedTracks( tracks );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::UpdatedTrack( int updatedby, const guTrack * track )
{
if( m_PlayerPanel && ( updatedby != guUPDATED_TRACKS_PLAYER ) )
{
m_PlayerPanel->UpdatedTrack( track );
}
if( m_PlayerPlayList && ( updatedby != guUPDATED_TRACKS_PLAYER_PLAYLIST ) )
{
m_PlayerPlayList->UpdatedTrack( track );
}
if( track->m_MediaViewer )
{
track->m_MediaViewer->UpdatedTrack( updatedby, track );
}
else if( track->m_Type == guTRACK_TYPE_PODCAST )
{
m_PodcastsPanel->UpdateTrack( track );
}
// if( m_LibPanel && ( updatedby != guUPDATED_TRACKS_LIBRARY ) )
// {
// m_LibPanel->UpdatedTrack( track );
// }
// if( m_PlayListPanel && ( updatedby != guUPDATED_TRACKS_PLAYLISTS ) )
// {
// m_PlayListPanel->UpdatedTrack( track );
// }
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLibraryCoverChanged( wxCommandEvent &event )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) event.GetClientData();
if( m_PlayerPanel )
{
const guCurrentTrack * CurrentTrack = m_PlayerPanel->GetCurrentTrack();
if( ( CurrentTrack->m_MediaViewer == MediaViewer ) && CurrentTrack->m_AlbumId == event.GetInt() )
{
m_PlayerPanel->UpdateCover( false, bool( event.GetExtraLong() ) );
}
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnPlayerPanelCoverChanged( wxCommandEvent &event )
{
if( m_CoverPanel )
{
m_CoverPanel->OnUpdatedTrack( event );
}
if( m_MPRIS2 )
{
m_MPRIS2->OnPlayerTrackChange();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CreateCopyToMenu( wxMenu * menu )
{
int Count;
wxMenuItem * MenuItem;
wxMenu * SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString CopyToOptions = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
if( ( Count = CopyToOptions.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
wxArrayString CurOption = wxStringTokenize( CopyToOptions[ Index ], wxT( ":") );
MenuItem = new wxMenuItem( SubMenu, ID_COPYTO_BASE + Index, unescape_configlist_str( CurOption[ 0 ] ), _( "Copy the current selected songs to a directory or device" ) );
SubMenu->Append( MenuItem );
}
}
bool SeparatorAdded = false;
Count = m_MediaViewers.Count();
for( int Index = 0; Index < Count; Index++ )
{
guMediaViewer * MediaViewer = m_MediaViewers[ Index ];
int Type = MediaViewer->GetType();
if( ( ( Type == guMEDIA_COLLECTION_TYPE_NORMAL ) && !MediaViewer->GetDefaultCopyAction().IsEmpty() ) ||
( Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( Type == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
if( !SeparatorAdded && SubMenu->GetMenuItemCount() )
{
SubMenu->AppendSeparator();
SeparatorAdded = true;
}
MenuItem = new wxMenuItem( SubMenu, ID_COPYTO_BASE + guCOPYTO_DEVICE_BASE + Index, MediaViewer->GetName(), _( "Copy the current selected songs to a directory or device" ) );
//MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_copy ) );
SubMenu->Append( MenuItem );
}
}
if( SubMenu->GetMenuItemCount() )
{
SubMenu->AppendSeparator();
}
MenuItem = new wxMenuItem( SubMenu, ID_MENU_PREFERENCES_COPYTO, _( "Preferences" ), _( "Add Copy To patterns in preferences" ) );
SubMenu->Append( MenuItem );
menu->AppendSubMenu( SubMenu, _( "Copy To..." ), _( "Copy the selected tracks to a folder or device" ) );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CopyToThreadFinished( void )
{
if( m_CopyToThread )
{
m_CopyToThreadMutex.Lock();
m_CopyToThread = NULL;
m_CopyToThreadMutex.Unlock();
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSetForceGapless( wxCommandEvent &event )
{
//guLogMessage( wxT( "OnSetForceGapless( %i )" ), event.GetInt() );
const bool IsEnable = event.GetInt();
m_MenuForceGapless->Check( IsEnable );
m_PlayerPanel->SetForceGapless( IsEnable );
/*
if( m_MainStatusBar )
{
m_MainStatusBar->SetPlayMode( IsEnable );
}
*/
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSetAudioScrobble( wxCommandEvent &event )
{
//guLogMessage( wxT( "OnSetAudioScrobble( %i )" ), event.GetInt() );
const bool IsEnable = event.GetInt();
if( m_MainStatusBar )
{
m_MainStatusBar->SetAudioScrobble( IsEnable );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLyricFound( wxCommandEvent &event )
{
//guLogMessage( wxT( "guMainFrame::OnLyricFound" ) );
wxString * LyricText = ( wxString * ) event.GetClientData();
if( m_LyricsPanel )
{
m_LyricsPanel->SetLyricText( LyricText );
m_LyricsPanel->SetLastSource( event.GetInt() );
}
if( LyricText )
{
delete LyricText;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLyricSearchFirst( wxCommandEvent &event )
{
if( m_LyricSearchEngine && m_LyricSearchContext )
{
m_LyricSearchContext->ResetIndex();
m_LyricSearchEngine->SearchStart( m_LyricSearchContext );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLyricSearchNext( wxCommandEvent &event )
{
if( m_LyricSearchEngine && m_LyricSearchContext )
{
m_LyricSearchEngine->SearchStart( m_LyricSearchContext );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLyricSaveChanges( wxCommandEvent &event )
{
if( m_LyricSearchEngine && m_LyricSearchContext )
{
wxString * LyricText = ( wxString * ) event.GetClientData();
m_LyricSearchEngine->SetLyricText( m_LyricSearchContext, * LyricText );
delete LyricText;
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLyricExecCommand( wxCommandEvent &event )
{
guLyricSearchThread * LyricSearchThread = ( guLyricSearchThread * ) event.GetClientObject();
wxString * CommandText = ( wxString * ) event.GetClientData();
guLogMessage( wxT( "OnLyricExecCommand: '%s'" ), CommandText->c_str() );
if( CommandText && !CommandText->IsEmpty() && LyricSearchThread )
{
guLyricExecCommandTerminate * LyricExecCommandTerminate = new guLyricExecCommandTerminate( LyricSearchThread, event.GetInt() );
if( LyricExecCommandTerminate )
{
if( !wxExecute( * CommandText, wxEXEC_ASYNC, LyricExecCommandTerminate ) )
{
guLogError( wxT( "Could not execute the command '%s'" ), CommandText->c_str() );
delete LyricExecCommandTerminate;
LyricSearchThread->FinishExecCommand( wxEmptyString );
}
else
{
LyricSearchThread->SetNotificationPtr( LyricExecCommandTerminate->GetNotificationPtr() );
}
LyricExecCommandTerminate->Redirect();
}
}
else
{
guLogMessage( wxT( "Error on OnLyricExecCommand..." ) );
}
delete CommandText;
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
guAccelOnConfigUpdated();
wxMenuBar * OldMenu = GetMenuBar();
CreateMenu();
delete OldMenu;
}
if( Flags & guPREFERENCE_PAGE_FLAG_LIBRARY )
{
m_CollectionsMutex.Lock();
guConfig * Config = ( guConfig * ) guConfig::Get();
guMediaCollectionArray Collections;
Config->LoadCollections( &Collections, guMEDIA_COLLECTION_TYPE_NORMAL );
Config->LoadCollections( &Collections, guMEDIA_COLLECTION_TYPE_JAMENDO );
Config->LoadCollections( &Collections, guMEDIA_COLLECTION_TYPE_MAGNATUNE );
Config->LoadCollections( &Collections, guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE );
Config->LoadCollections( &Collections, guMEDIA_COLLECTION_TYPE_IPOD );
//wxArrayInt DeletedIndex;
int Count = m_Collections.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( FindCollectionUniqueId( &Collections, m_Collections[ Index ].m_UniqueId ) == wxNOT_FOUND )
{
guMediaViewer * MediaViewer = FindCollectionMediaViewer( m_Collections[ Index ].m_UniqueId );
if( MediaViewer )
{
event.SetId( ID_COLLECTIONS_BASE + ( Index * guCOLLECTION_ACTION_COUNT ) );
event.SetInt( 0 );
OnCollectionCommand( event );
}
//DeletedIndex.Add( Index );
}
}
m_Collections = Collections;
Count = m_Collections.Count();
int CollectionBaseCommand = ID_COLLECTIONS_BASE;
for( int Index = 0; Index < Count; Index++ )
{
guMediaCollection &Collection = m_Collections[ Index ];
guMediaViewer * MediaViewer = FindCollectionMediaViewer( Collection.m_UniqueId );
if( MediaViewer )
{
guLogMessage( wxT( "Setting new collection to '%s' => '%s'" ), MediaViewer->GetName().c_str(), Collection.m_Name.c_str() );
MediaViewer->SetCollection( Collection, CollectionBaseCommand );
}
CollectionBaseCommand += guCOLLECTION_ACTION_COUNT;
}
m_CollectionsMutex.Unlock();
CollectionsUpdated();
}
if( ( Flags & guPREFERENCE_PAGE_FLAG_LYRICS ) && m_LyricSearchEngine )
{
m_LyricSearchEngine->Load();
}
if( Flags & guPREFERENCE_PAGE_FLAG_AUDIOSCROBBLE )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
bool AudioScrobbleEnabled = Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM ) ||
Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM );
m_MenuAudioScrobble->Check( AudioScrobbleEnabled );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSongSetRating( wxCommandEvent &event )
{
int Rating = event.GetId() - ID_PLAYERPANEL_SETRATING_0;
//guLogMessage( wxT( "Set rating to %i" ), Rating );
if( m_PlayerPanel )
{
m_PlayerPanel->SetRating( Rating );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnSetAllowDenyFilter( wxCommandEvent &event )
{
if( ( event.GetId() == ID_MAINFRAME_SET_ALLOW_PLAYLIST ) )
{
m_PlayerFilters->SetAllowFilterId( event.GetInt() );
}
else
{
m_PlayerFilters->SetDenyFilterId( event.GetInt() );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnRaiseWindow( wxCommandEvent &event )
{
//guLogMessage( wxT( "guMainFrame::OnRaiseWindow" ) );
if( !IsShown() )
Show( true );
if( IsIconized() )
Iconize( false );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::OnLoadPlayList( wxCommandEvent &event )
{
//guLogMessage( wxT( "OnLoadPlaylist %i " ), event.GetInt() );
guTrackArray Tracks;
if( m_Db->GetPlayListSongs( event.GetInt(), &Tracks ) )
{
m_PlayerPanel->SetPlayList( Tracks );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::SaveCollections( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->SaveCollections( &m_Collections );
Config->Flush();
}
// -------------------------------------------------------------------------------- //
void inline AddCollectionCoverNames( wxArrayString &covernames, const guMediaCollection &mediacollection )
{
int Count = mediacollection.m_CoverWords.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxString CoverName = mediacollection.m_CoverWords[ Index ];
if( covernames.Index( CoverName ) == wxNOT_FOUND )
covernames.Add( CoverName );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::GetCollectionsCoverNames( wxArrayString &covernames )
{
int Count = m_Collections.Count();
for( int Index = 0; Index < Count; Index++ )
{
AddCollectionCoverNames( covernames, m_Collections[ Index ] );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::MediaViewerCreated( const wxString &uniqueid, guMediaViewer * mediaviewer )
{
if( m_PlayerPlayList )
{
m_PlayerPlayList->MediaViewerCreated( uniqueid, mediaviewer );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::MediaViewerClosed( guMediaViewer * mediaviewer )
{
if( m_PlayerPanel )
{
m_PlayerPanel->MediaViewerClosed( mediaviewer );
}
if( m_PlayerPlayList )
{
m_PlayerPlayList->MediaViewerClosed( mediaviewer );
}
if( m_LastFMPanel )
{
m_LastFMPanel->MediaViewerClosed( mediaviewer );
}
}
// -------------------------------------------------------------------------------- //
void guMainFrame::AddPendingUpdateTrack( const guTrack &track, const wxImage * image, const wxString &lyric, const int changedflags )
{
guLogMessage( wxT( "Adding pending update track '%s'" ), track.m_FileName.c_str() );
wxMutexLocker Lock( m_PendingUpdateMutex );
m_PendingUpdateTracks.Insert( new guTrack( track ), 0 );
m_PendingUpdateFiles.Insert( wxEmptyString, 0 );
m_PendingUpdateImages.Insert( image ? new wxImage( * image ) : NULL, 0 );
m_PendingUpdateLyrics.Insert( lyric, 0 );
m_PendingUpdateFlags.Insert( changedflags, 0 );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::AddPendingUpdateTrack( const wxString &filename, const wxImage * image, const wxString &lyric, const int changedflags )
{
guLogMessage( wxT( "Adding pending update file '%s'" ), filename.c_str() );
wxMutexLocker Lock( m_PendingUpdateMutex );
m_PendingUpdateTracks.Insert( NULL, 0 );
m_PendingUpdateFiles.Insert( filename, 0 );
m_PendingUpdateImages.Insert( image ? new wxImage( * image ) : NULL, 0 );
m_PendingUpdateLyrics.Insert( lyric, 0 );
m_PendingUpdateFlags.Insert( changedflags, 0 );
}
// -------------------------------------------------------------------------------- //
void guMainFrame::CheckPendingUpdates( const guTrack * track, const bool forcesave )
{
wxMutexLocker Lock( m_PendingUpdateMutex );
int Count = m_PendingUpdateTracks.Count();
if( Count )
{
for( int Index = Count - 1; Index >= 0; Index-- )
{
bool RemoveTrack = false;
wxString CurFile = m_PendingUpdateFiles[ Index ];
if( CurFile.IsEmpty() )
{
CurFile = m_PendingUpdateTracks[ Index ].m_FileName;
if( forcesave || ( CurFile != track->m_FileName ) )
{
guTrackArray Tracks;
Tracks.Add( m_PendingUpdateTracks[ Index ] );
guImagePtrArray Images;
Images.Add( m_PendingUpdateImages[ Index ] );
wxArrayString Lyrics;
Lyrics.Add( m_PendingUpdateLyrics[ Index ] );
wxArrayInt ChangedFlags;
ChangedFlags.Add( m_PendingUpdateFlags[ Index ] );
guUpdateTracks( Tracks, Images, Lyrics, ChangedFlags, forcesave );
RemoveTrack = true;
}
}
else
{
if( forcesave || ( CurFile != track->m_FileName ) )
{
int ChangedFlags = m_PendingUpdateFlags[ Index ];
if( ChangedFlags == guTRACK_CHANGED_DATA_LYRICS )
{
guTagSetLyrics( CurFile, m_PendingUpdateLyrics[ Index ], forcesave );
}
else
{
guTagSetPicture( CurFile, m_PendingUpdateImages[ Index ], forcesave );
}
RemoveTrack = true;
}
}
if( RemoveTrack )
{
m_PendingUpdateTracks.RemoveAt( Index );
m_PendingUpdateFiles.RemoveAt( Index );
m_PendingUpdateImages.RemoveAt( Index );
m_PendingUpdateLyrics.RemoveAt( Index );
m_PendingUpdateFlags.RemoveAt( Index );
}
}
}
}
// -------------------------------------------------------------------------------- //
// guUpdatePodcastsTimer
// -------------------------------------------------------------------------------- //
guUpdatePodcastsTimer::guUpdatePodcastsTimer( guMainFrame * mainframe, guDbLibrary * db ) : wxTimer()
{
m_MainFrame = mainframe;
m_Db = db;
}
// -------------------------------------------------------------------------------- //
void guUpdatePodcastsTimer::Notify()
{
m_MainFrame->UpdatePodcasts();
}
// -------------------------------------------------------------------------------- //
// guUpdatePodcastThread
// -------------------------------------------------------------------------------- //
guUpdatePodcastsThread::guUpdatePodcastsThread( guMainFrame * mainframe,
int gaugeid ) : wxThread()
{
m_MainFrame = mainframe;
m_GaugeId = gaugeid;
m_Db = mainframe->GetPodcastsDb();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guUpdatePodcastsThread::~guUpdatePodcastsThread()
{
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
event.SetInt( m_GaugeId );
wxPostEvent( m_MainFrame, event );
}
// -------------------------------------------------------------------------------- //
guUpdatePodcastsThread::ExitCode guUpdatePodcastsThread::Entry()
{
guPodcastChannelArray PodcastChannels;
if( m_Db->GetPodcastChannels( &PodcastChannels ) )
{
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
event.SetInt( m_GaugeId );
event.SetExtraLong( PodcastChannels.Count() );
wxPostEvent( m_MainFrame, event );
unsigned int Index = 0;
while( !TestDestroy() && Index < PodcastChannels.Count() )
{
event.SetId( ID_STATUSBAR_GAUGE_UPDATE );
event.SetInt( m_GaugeId );
event.SetExtraLong( Index + 1 );
wxPostEvent( m_MainFrame, event );
PodcastChannels[ Index ].Update( m_Db, m_MainFrame );
Index++;
Sleep( 20 );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 192,264
|
C++
|
.cpp
| 4,238
| 36.463662
| 205
| 0.568242
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,580
|
Jamendo.cpp
|
anonbeat_guayadeque/src/ui/jamendo/Jamendo.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Jamendo.h"
#include "TagInfo.h"
#include "MainFrame.h"
#include "SelCoverFile.h"
#include "StatusBar.h"
#include <wx/wfstream.h>
#include <wx/mstream.h>
#include <wx/zstream.h>
#include <wx/xml/xml.h>
#include <id3v1genres.h>
//
// Data not in the dump but easily fetchable with the IDs
//
// (Please replace {TRACKID} and {ALBUMID} in these urls by the numeric IDs found in the dump)
//
// * MP3s for streaming : http://api.jamendo.com/get2/stream/track/redirect/?id={TRACKID}&streamencoding=mp31
// * OGGs for streaming : http://api.jamendo.com/get2/stream/track/redirect/?id={TRACKID}&streamencoding=ogg2
//
// * .torrent file for download (MP3 archive) : http://api.jamendo.com/get2/bittorrent/file/plain/?album_id={ALBUMID}&type=archive&class=mp32
// * .torrent file for download (OGG archive) : http://api.jamendo.com/get2/bittorrent/file/plain/?album_id={ALBUMID}&type=archive&class=ogg3
//
// * Album Covers are available here: http://api.jamendo.com/get2/image/album/redirect/?id={ALBUMID}&imagesize={100-600}
//
//
// To download directly in zip format
// http://www.jamendo.com/en/download/album/57557
// >> http://download25.jamendo.com/request/album/61518/mp32/fabc1123
// << Jamendo_HttpDownloadCallback('ready','fb267e3f92');
// >> http://download25.jamendo.com/download/album/61518/mp32/"+data+"/"+encodeURIComponent("noblemo - PIANO -- Jamendo - MP3 VBR 192k - 2010.02.16 [www.jamendo.com].zip")
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
// guJamendoLibrary
// -------------------------------------------------------------------------------- //
guJamendoLibrary::guJamendoLibrary( const wxString &dbname ) :
guDbLibrary( dbname )
{
}
// -------------------------------------------------------------------------------- //
guJamendoLibrary::~guJamendoLibrary()
{
}
// -------------------------------------------------------------------------------- //
void guJamendoLibrary::UpdateArtistsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ArIndex;
int ArCount = labelsets.Count();
for( ArIndex = 0; ArIndex < ArCount; ArIndex++ )
{
wxArrayInt ArLabels = labelsets[ ArIndex ].GetData();
//guLogMessage( wxT( "Artist Labels : '%s'" ), ArtistLabelStr.c_str() );
// Update the Database
wxArrayInt Artists;
Artists.Add( labelsets[ ArIndex ].GetId() );
SetArtistsLabels( Artists, ArLabels );
}
}
// -------------------------------------------------------------------------------- //
void guJamendoLibrary::UpdateSongsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ItemIndex;
int ItemCount = labelsets.Count();
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
wxArrayInt ItemLabels = labelsets[ ItemIndex ].GetData();
//guLogMessage( wxT( "Artist Labels : '%s'" ), ArtistLabelStr.c_str() );
// Update the Database
wxArrayInt ItemIds;
ItemIds.Add( labelsets[ ItemIndex ].GetId() );
SetSongsLabels( ItemIds, ItemLabels );
}
}
// -------------------------------------------------------------------------------- //
void guJamendoLibrary::UpdateAlbumsLabels( const guArrayListItems &labelsets )
{
guListItems LaItems;
// The ArtistLabels string is the same for all songs so done out of the loop
GetLabels( &LaItems, true );
int ItemIndex;
int ItemCount = labelsets.Count();
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
wxArrayInt ItemLabels = labelsets[ ItemIndex ].GetData();
//guLogMessage( wxT( "Artist Labels : '%s'" ), ArtistLabelStr.c_str() );
// Update the Database
wxArrayInt ItemIds;
ItemIds.Add( labelsets[ ItemIndex ].GetId() );
SetAlbumsLabels( ItemIds, ItemLabels );
}
}
// -------------------------------------------------------------------------------- //
void guJamendoLibrary::CreateNewSong( guTrack * track )
{
wxString query;
wxSQLite3ResultSet dbRes;
track->m_Path = track->m_GenreName + wxT( "/" ) +
track->m_ArtistName + wxT( "/" ) +
track->m_AlbumName + wxT( "/" );
track->m_PathId = GetPathId( track->m_Path );
query = wxString::Format( wxT( "SELECT song_id FROM songs WHERE song_id = %i LIMIT 1;" ), track->m_SongId );
dbRes = ExecuteQuery( query );
if( !dbRes.NextRow() )
{
wxString query = wxString::Format( wxT( "INSERT INTO songs( " \
"song_id, song_playcount, song_addedtime, " \
"song_name, song_genreid, song_genre, song_artistid, song_artist, " \
"song_albumid, song_album, song_pathid, song_path, song_filename, song_format, song_number, song_year, " \
"song_coverid, song_disk, song_length, song_offset, song_bitrate, song_rating, " \
"song_filesize ) VALUES( %u, 0, %lu, '%s', %u, '%s', %u, '%s', %u, '%s', " \
"%u, '%s', '%s', 'mp3,ogg', %u, %u, %u, '%s', %u, 0, 0, -1, 0 )" ),
track->m_SongId,
wxDateTime::GetTimeNow(),
escape_query_str( track->m_SongName ).c_str(),
track->m_GenreId,
escape_query_str( track->m_GenreName ).c_str(),
track->m_ArtistId,
escape_query_str( track->m_ArtistName ).c_str(),
track->m_AlbumId,
escape_query_str( track->m_AlbumName ).c_str(),
track->m_PathId,
escape_query_str( track->m_Path ).c_str(),
escape_query_str( track->m_FileName ).c_str(),
track->m_Number,
track->m_Year,
track->m_CoverId,
escape_query_str( track->m_Disk ).c_str(),
track->m_Length );
//guLogMessage( wxT( "%s" ), query.c_str() );
ExecuteUpdate( query );
}
// guLogMessage( wxT( "%s/%s/%s/%i - %s" ),
// track->m_GenreName.c_str(),
// track->m_ArtistName.c_str(),
// track->m_AlbumName.c_str(),
// track->m_Number,
// track->m_SongName.c_str() );
}
// -------------------------------------------------------------------------------- //
// guJamendoPanel
// -------------------------------------------------------------------------------- //
guJamendoPanel::guJamendoPanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guLibPanel( parent, mediaviewer )
{
Bind( wxEVT_MENU, &guJamendoPanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Bind( wxEVT_MENU, &guJamendoPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
Bind( wxEVT_MENU, &guJamendoPanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
Bind( wxEVT_MENU, &guJamendoPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
guJamendoPanel::~guJamendoPanel()
{
Unbind( wxEVT_MENU, &guJamendoPanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Unbind( wxEVT_MENU, &guJamendoPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
Unbind( wxEVT_MENU, &guJamendoPanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
Unbind( wxEVT_MENU, &guJamendoPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
void guJamendoPanel::OnDownloadAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadAlbum" ) );
wxArrayInt Albums = m_AlbumListCtrl->GetSelectedItems();
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM ) );
}
// -------------------------------------------------------------------------------- //
void guJamendoPanel::OnDownloadTrackAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadTrackAlbum" ) );
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt Albums;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Albums.Index( Tracks[ Index ].m_AlbumId ) == wxNOT_FOUND )
Albums.Add( Tracks[ Index ].m_AlbumId );
}
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM ) );
}
// -------------------------------------------------------------------------------- //
// guJamendoDownloadThread
// -------------------------------------------------------------------------------- //
guJamendoDownloadThread::guJamendoDownloadThread( guMediaViewerJamendo * mediaviewer )
{
m_MediaViewer = mediaviewer;
m_Db = ( guJamendoLibrary * ) mediaviewer->GetDb();
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guJamendoDownloadThread::~guJamendoDownloadThread()
{
if( !TestDestroy() )
{
m_MediaViewer->EndDownloadThread();
}
}
// -------------------------------------------------------------------------------- //
void guJamendoDownloadThread::AddAlbum( const int albumid, const bool iscover )
{
if( iscover )
{
m_CoversMutex.Lock();
m_Covers.Add( albumid );
m_CoversMutex.Unlock();
}
else
{
m_AlbumsMutex.Lock();
m_Albums.Add( albumid );
m_AlbumsMutex.Unlock();
}
}
// -------------------------------------------------------------------------------- //
void guJamendoDownloadThread::AddAlbums( const wxArrayInt &albumids, const bool iscover )
{
int Count = albumids.Count();
if( iscover )
{
m_CoversMutex.Lock();
for( int Index = 0; Index < Count; Index++ )
{
m_Covers.Add( albumids[ Index ] );
}
m_CoversMutex.Unlock();
}
else
{
m_AlbumsMutex.Lock();
for( int Index = 0; Index < Count; Index++ )
{
m_Albums.Add( albumids[ Index ] );
}
m_AlbumsMutex.Unlock();
}
}
// -------------------------------------------------------------------------------- //
guJamendoDownloadThread::ExitCode guJamendoDownloadThread::Entry()
{
int Count;
int LoopCount = 0;
guConfig * Config = ( guConfig * ) guConfig::Get();
int AudioFormat = Config->ReadNum( CONFIG_KEY_JAMENDO_AUDIOFORMAT, 1, CONFIG_PATH_JAMENDO );
wxString TorrentCmd = Config->ReadStr( CONFIG_KEY_JAMENDO_TORRENT_COMMAND, wxEmptyString, CONFIG_PATH_JAMENDO );
while( !TestDestroy() )
{
m_CoversMutex.Lock();
Count = m_Covers.Count();
m_CoversMutex.Unlock();
size_t CurTime = wxGetLocalTimeMillis().GetLo();
if( Count )
{
LoopCount = 0;
wxString CoverFile = guPATH_JAMENDO_COVERS;
CoverFile += wxString::Format( wxT( "%u.jpg" ), m_Covers[ 0 ] );
if( !wxFileExists( CoverFile ) )
{
if( !wxDirExists( wxPathOnly( CoverFile ) + wxT( "/" ) ) )
{
wxMkdir( wxPathOnly( CoverFile ) + wxT( "/" ), 0770 );
}
wxString CoverUrl = wxString::Format( guJAMENDO_COVER_DOWNLOAD_URL, m_Covers[ 0 ], 300 );
DownloadImage( CoverUrl, CoverFile, 300 );
}
if( wxFileExists( CoverFile ) )
{
int CoverId = m_Db->AddCoverFile( CoverFile );
wxString query = wxString::Format( wxT( "UPDATE songs SET song_coverid = %u WHERE song_albumid = %u" ),
CoverId, m_Covers[ 0 ] );
m_Db->ExecuteUpdate( query );
// Notify the panel that the cover is downloaded
wxCommandEvent event( wxEVT_MENU, ID_JAMENDO_COVER_DOWNLAODED );
event.SetInt( m_Covers[ 0 ] );
wxPostEvent( m_MediaViewer, event );
}
else
{
guLogMessage( wxT( "Could not get the jamendo cover art %s" ), CoverFile.c_str() );
}
m_CoversMutex.Lock();
m_Covers.RemoveAt( 0 );
m_CoversMutex.Unlock();
}
else
{
LoopCount++;
if( LoopCount > 8 )
{
break;
}
}
if( TestDestroy() )
break;
size_t Elapsed = wxGetLocalTimeMillis().GetLo() - CurTime;
if( !( Elapsed > 1000 ) )
{
Sleep( 1000 - Elapsed );
}
//
// Album Torrents
//
m_AlbumsMutex.Lock();
Count = m_Albums.Count();
m_AlbumsMutex.Unlock();
CurTime = wxGetLocalTimeMillis().GetLo();
if( Count )
{
LoopCount = 0;
wxString Url = wxString::Format( guJAMENDO_TORRENT_DOWNLOAD_URL, m_Albums[ 0 ] );
Url += AudioFormat ? guJAMENDO_DOWNLOAD_FORMAT_OGG : guJAMENDO_DOWNLOAD_FORMAT_MP3;
//guLogMessage( wxT( "Getting %s" ), Url.c_str() );
wxString TorrentUrl = GetUrlContent( Url );
//guLogMessage( wxT( "Downloading '%s'" ), TorrentUrl.c_str() );
if( !TorrentUrl.IsEmpty() )
{
wxString TmpFileName = wxFileName::CreateTempFileName( wxString::Format( wxT( "%u" ), m_Albums[ 0 ] ) );
TmpFileName += wxT( ".torrent" );
if( DownloadFile( TorrentUrl, TmpFileName ) )
{
guExecute( TorrentCmd + wxT( " " ) + TmpFileName );
}
}
m_AlbumsMutex.Lock();
m_Albums.RemoveAt( 0 );
m_AlbumsMutex.Unlock();
}
else
{
LoopCount++;
if( LoopCount > 8 )
{
break;
}
}
if( TestDestroy() )
break;
Elapsed = wxGetLocalTimeMillis().GetLo() - CurTime;
if( !( Elapsed > 1000 ) )
{
Sleep( 1000 - Elapsed );
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guJamendoUpdateThread
// -------------------------------------------------------------------------------- //
guJamendoUpdateThread::guJamendoUpdateThread( guMediaViewerJamendo * mediaviewer, int action, int gaugeid )
{
m_MediaViewer = mediaviewer;
m_Db = ( guJamendoLibrary * ) mediaviewer->GetDb();
m_MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
m_Action = action;
m_GaugeId = gaugeid;
guConfig * Config = ( guConfig * ) guConfig::Get();
m_AllowedGenres = Config->ReadANum( CONFIG_KEY_JAMENDO_GENRES_GENRE, 0, CONFIG_PATH_JAMENDO_GENRES );
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 10 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guJamendoUpdateThread::~guJamendoUpdateThread()
{
//
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
event.SetInt( m_GaugeId );
wxPostEvent( m_MainFrame, event );
if( !TestDestroy() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxDateTime Now = wxDateTime::Now();
Config->WriteNum( CONFIG_KEY_JAMENDO_LAST_UPDATE, Now.GetTicks(), CONFIG_PATH_JAMENDO );
Config->Flush();
}
event.SetId( ID_JAMENDO_UPDATE_FINISHED );
event.SetEventObject( ( wxObject * ) this );
wxPostEvent( m_MediaViewer, event );
}
}
/*
<JamendoData epoch="1282819258" documentation="http://developer.jamendo.com/en/wiki/DatabaseDumps" type="artistalbumtrack">
<Artists>
<artist>
<id>338334</id>
<name>0/20</name>
<url>http://www.jamendo.com/artist/0_20</url>
<mbgid></mbgid>
<location>
<country>ECU</country>
<state></state>
<city>QUITO</city>
<latitude>-0.229498</latitude>
<longitude>-78.5243</longitude>
</location>
<Albums>
<album>
<id>19831</id>
<name>!Ya Estoy Harto de Mis Profesores¡¡¡¡¡¡¡(DEMO VERSION)</name>
<url>http://www.jamendo.com/album/19831</url>
<releasedate>2008-02-29T15:29:52+01:00</releasedate>
<filename>0 20 - !Ya Estoy Harto de Mis Profesores DEMO VERSION</filename>
<id3genre>43</id3genre>
<mbgid></mbgid>
<license_artwork>http://creativecommons.org/licenses/by-sa/3.0/</license_artwork>
<Tracks>
<track><id>138701</id>
<name>Odio Estudiar</name>
<duration>40</duration>
<numalbum>1</numalbum>
<filename>01 - 0 20 - Odio Estudiar</filename>
<mbgid></mbgid>
<id3genre>43</id3genre>
<license>http://creativecommons.org/licenses/by-sa/3.0/</license>
</track>
<track>
<id>138702</id>
<name>Turro Colegio</name>
<duration>145</duration>
<numalbum>2</numalbum>
<filename>02 - 0 20 - Turro Colegio</filename>
<mbgid></mbgid>
<id3genre>40</id3genre>
<license>http://creativecommons.org/licenses/by-sa/3.0/</license>
</track>
</Tracks>
</album>
</Albums>
</artist>
...
</Artists>
*/
// -------------------------------------------------------------------------------- //
void ReadJamendoXmlTrack( wxXmlNode * xmlnode, guJamendoUpdateThread * thread, guTrack * track )
{
long Id;
while( xmlnode && !thread->TestDestroy() )
{
wxString ItemName = xmlnode->GetName();
if( ItemName == wxT( "id" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_SongId = Id;
}
else if( ItemName == wxT( "name" ) )
{
track->m_SongName = xmlnode->GetNodeContent().Trim( true ).Trim( false );
}
else if( ItemName == wxT( "duration" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_Length = Id * 1000;
}
else if( ItemName == wxT( "numalbum" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_Number = Id;
}
else if( ItemName == wxT( "filename" ) )
{
track->m_FileName = xmlnode->GetNodeContent();
}
else if( ItemName == wxT( "id3genre" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_GenreName = TStringTowxString( TagLib::ID3v1::genre( Id ) );
track->m_GenreId = Id + 1; // Avoid use Id 0 ('Blues') as for us its 'All Genres'
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadJamendoXmlTracks( wxXmlNode * xmlnode, guJamendoUpdateThread * thread, guTrack * track, guJamendoLibrary * db, wxArrayInt &genres )
{
while( xmlnode && !thread->TestDestroy() )
{
if( xmlnode->GetName() == wxT( "track" ) )
{
ReadJamendoXmlTrack( xmlnode->GetChildren(), thread, track );
if( genres.Index( track->m_GenreId - 1 ) != wxNOT_FOUND )
{
db->CreateNewSong( track );
}
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadJamendoXmlAlbum( wxXmlNode * xmlnode, guJamendoUpdateThread * thread, guTrack * track, guJamendoLibrary * db, wxArrayInt &genres )
{
long Id;
while( xmlnode && !thread->TestDestroy() )
{
wxString ItemName = xmlnode->GetName();
if( ItemName == wxT( "id" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_AlbumId = Id;
}
else if( ItemName == wxT( "name" ) )
{
track->m_AlbumName = xmlnode->GetNodeContent().Trim( true ).Trim( false );
}
else if( ItemName == wxT( "releasedate" ) )
{
wxString ReleaseDate = xmlnode->GetNodeContent();
if( !ReleaseDate.IsEmpty() )
{
ReleaseDate.Mid( 0, 4 ).ToLong( &Id );
track->m_Year = Id;
}
}
else if( ItemName == wxT( "id3genre" ) )
{
xmlnode->GetNodeContent().ToLong( &Id );
track->m_GenreName = TStringTowxString( TagLib::ID3v1::genre( Id ) );
track->m_GenreId = Id + 1; // Avoid use Id 0 ('Blues') as for us its 'All Genres'
}
else if( ItemName == wxT( "Tracks" ) )
{
ReadJamendoXmlTracks( xmlnode->GetChildren(), thread, track, db, genres );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadJamendoXmlAlbums( wxXmlNode * xmlnode, guJamendoUpdateThread * thread, guTrack * track, guJamendoLibrary * db, wxArrayInt &genres )
{
while( xmlnode && !thread->TestDestroy() )
{
if( xmlnode->GetName() == wxT( "album" ) )
{
track->m_CoverId = 0;
track->m_GenreName = _( "Unknown" );
track->m_GenreId = 10000;
ReadJamendoXmlAlbum( xmlnode->GetChildren(), thread, track, db, genres );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void ReadJamendoXmlArtist( wxXmlNode * xmlnode, guJamendoUpdateThread * thread, guTrack * track, guJamendoLibrary * db, wxArrayInt &genres )
{
while( xmlnode && !thread->TestDestroy() )
{
wxString ItemName = xmlnode->GetName();
if( ItemName == wxT( "id" ) )
{
long Id;
xmlnode->GetNodeContent().ToLong( &Id );
track->m_ArtistId = Id;
}
else if( ItemName == wxT( "name" ) )
{
track->m_ArtistName = xmlnode->GetNodeContent().Trim( true ).Trim( false );
guLogMessage( wxT( "Artist: '%s'" ), track->m_ArtistName.c_str() );
}
else if( ItemName == wxT( "Albums" ) )
{
ReadJamendoXmlAlbums( xmlnode->GetChildren(), thread, track, db, genres );
}
xmlnode = xmlnode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
bool guJamendoUpdateThread::UpgradeDatabase( void )
{
if( DownloadFile( guJAMENDO_DATABASE_DUMP_URL, guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml.gz" ) ) )
{
wxFileInputStream Ins( guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml.gz" ) );
if( Ins.IsOk() )
{
wxZlibInputStream ZIn( Ins );
if( ZIn.IsOk() )
{
wxFileOutputStream ZOuts( guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml" ) );
if( ZOuts.IsOk() )
{
ZIn.Read( ZOuts );
return true;
}
}
}
else
{
guLogError( wxT( "Could not open the Jamendo local database copy" ) );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
guJamendoUpdateThread::ExitCode guJamendoUpdateThread::Entry()
{
wxString query;
wxCommandEvent evtup( wxEVT_MENU, ID_STATUSBAR_GAUGE_UPDATE );
evtup.SetInt( m_GaugeId );
wxCommandEvent evtmax( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
evtmax.SetInt( m_GaugeId );
if( m_Action == guJAMENDO_ACTION_UPDATE &&
!wxFileExists( guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml" ) ) )
{
m_Action = guJAMENDO_ACTION_UPGRADE;
}
guLogMessage( wxT( "Starting the Jamendo Update process..." ) );
if( !TestDestroy() && ( m_Action == guJAMENDO_ACTION_UPDATE || UpgradeDatabase() ) )
{
wxFile XmlFile( guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml" ), wxFile::read );
if( XmlFile.IsOpened() )
{
guListItems CurrentGenres;
m_Db->GetGenres( &CurrentGenres, true );
wxArrayInt GenresToDel;
int Count = CurrentGenres.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_AllowedGenres.Index( CurrentGenres[ Index ].m_Id - 1 ) == wxNOT_FOUND )
GenresToDel.Add( CurrentGenres[ Index ].m_Id );
}
// query = wxT( "BEGIN TRANSACTION" );
// m_Db->ExecuteUpdate( query );
if( GenresToDel.Count() )
{
guLogMessage( wxT( "Deleting old jamendo genres" ) );
query = wxT( "DELETE FROM songs WHERE " ) + ArrayToFilter( GenresToDel, wxT( "song_genreid" ) );
m_Db->ExecuteUpdate( query );
}
evtmax.SetExtraLong( XmlFile.Length() );
wxPostEvent( guMainFrame::GetMainFrame(), evtmax );
wxFileOffset CurPos;
if( m_AllowedGenres.Count() )
{
wxString ArtistChunk = guGetNextXMLChunk( XmlFile, CurPos, "<artist>", "</artist>" );
int LastTime = wxGetLocalTime() + 2;
while( !TestDestroy() && !ArtistChunk.IsEmpty() )
{
wxStringInputStream Ins( ArtistChunk );
wxXmlDocument XmlDoc( Ins );
if( XmlDoc.IsOk() )
{
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "artist" ) )
{
ReadJamendoXmlArtist( XmlNode->GetChildren(), this, &m_CurrentTrack, m_Db, m_AllowedGenres );
}
}
else
{
guLogMessage( wxT( "Error in artist chunk:\n%s" ), ArtistChunk.c_str() );
}
ArtistChunk = guGetNextXMLChunk( XmlFile, CurPos, "<artist>", "</artist>" );
if( wxGetLocalTime() > LastTime )
{
LastTime = wxGetLocalTime() + 2;
// query = wxT( "END TRANSACTION" );
// m_Db->ExecuteUpdate( query );
evtup.SetExtraLong( CurPos );
wxPostEvent( guMainFrame::GetMainFrame(), evtup );
// query = wxT( "BEGIN TRANSACTION" );
// m_Db->ExecuteUpdate( query );
}
}
}
// query = wxT( "END TRANSACTION" );
// m_Db->ExecuteUpdate( query );
XmlFile.Close();
}
else
{
guLogMessage( wxT( "Could not open the file %s" ), wxString( guPATH_JAMENDO wxT( "dbdump_artistalbumtrack.xml" ) ).c_str() );
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guJamendoAlbumBrowser
// -------------------------------------------------------------------------------- //
guJamendoAlbumBrowser::guJamendoAlbumBrowser( wxWindow * parent, guMediaViewer * mediaviewer ) :
guAlbumBrowser( parent, mediaviewer )
{
Bind( wxEVT_MENU, &guJamendoAlbumBrowser::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Bind( wxEVT_MENU, &guJamendoAlbumBrowser::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
}
// -------------------------------------------------------------------------------- //
guJamendoAlbumBrowser::~guJamendoAlbumBrowser()
{
Unbind( wxEVT_MENU, &guJamendoAlbumBrowser::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Unbind( wxEVT_MENU, &guJamendoAlbumBrowser::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
}
// -------------------------------------------------------------------------------- //
void guJamendoAlbumBrowser::OnDownloadAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadAlbum" ) );
if( m_LastAlbumBrowserItem )
{
wxArrayInt Albums;
Albums.Add( m_LastAlbumBrowserItem->m_AlbumId );
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM ) );
}
}
// -------------------------------------------------------------------------------- //
// guJamendoTreePanel
// -------------------------------------------------------------------------------- //
guJamendoTreePanel::guJamendoTreePanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guTreeViewPanel( parent, mediaviewer )
{
Bind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Bind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
Bind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
Bind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
guJamendoTreePanel::~guJamendoTreePanel()
{
Unbind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM );
Unbind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM );
Unbind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
Unbind( wxEVT_MENU, &guJamendoTreePanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
void guJamendoTreePanel::OnDownloadAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadAlbum" ) );
const wxTreeItemId &CurItemId = m_TreeViewCtrl->GetSelection();
guTreeViewData * TreeViewData = ( guTreeViewData * ) m_TreeViewCtrl->GetItemData( CurItemId );
int ItemType = TreeViewData->GetType();
if( ItemType == guLIBRARY_ELEMENT_ALBUMS )
{
wxArrayInt Albums;
Albums.Add( TreeViewData->m_Id );
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM ) );
}
}
// -------------------------------------------------------------------------------- //
void guJamendoTreePanel::OnDownloadTrackAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadTrackAlbum" ) );
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt Albums;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Albums.Index( Tracks[ Index ].m_AlbumId ) == wxNOT_FOUND )
Albums.Add( Tracks[ Index ].m_AlbumId );
}
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM ) );
}
// -------------------------------------------------------------------------------- //
// guJamendoPlayListPanel
// -------------------------------------------------------------------------------- //
guJamendoPlayListPanel::guJamendoPlayListPanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guPlayListPanel( parent, mediaviewer )
{
Bind( wxEVT_MENU, &guJamendoPlayListPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
Bind( wxEVT_MENU, &guJamendoPlayListPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
guJamendoPlayListPanel::~guJamendoPlayListPanel()
{
Unbind( wxEVT_MENU, &guJamendoPlayListPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM );
Unbind( wxEVT_MENU, &guJamendoPlayListPanel::OnDownloadTrackAlbum, this, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM );
}
// -------------------------------------------------------------------------------- //
void guJamendoPlayListPanel::OnDownloadTrackAlbum( wxCommandEvent &event )
{
guLogMessage( wxT( "OnDownloadTrackAlbum" ) );
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt Albums;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Albums.Index( Tracks[ Index ].m_AlbumId ) == wxNOT_FOUND )
Albums.Add( Tracks[ Index ].m_AlbumId );
}
( ( guMediaViewerJamendo * ) m_MediaViewer )->DownloadAlbums( Albums, ( event.GetId() == ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM ) );
}
// -------------------------------------------------------------------------------- //
// guMediaVIewerJamendo
// -------------------------------------------------------------------------------- //
guMediaViewerJamendo::guMediaViewerJamendo( wxWindow * parent, guMediaCollection &mediacollection,
const int basecmd, guMainFrame * mainframe, const int mode, guPlayerPanel * playerpanel ) :
guMediaViewer( parent, mediacollection, basecmd, mainframe, mode, playerpanel )
{
m_DownloadThread = NULL;
m_ContextMenuFlags = ( guCONTEXTMENU_DOWNLOAD_COVERS | guCONTEXTMENU_LINKS );
Bind( wxEVT_MENU, &guMediaViewerJamendo::OnCoverDownloaded, this, ID_JAMENDO_COVER_DOWNLAODED );
Bind( wxEVT_MENU, &guMediaViewerJamendo::OnUpdateFinished, this, ID_JAMENDO_UPDATE_FINISHED );
InitMediaViewer( mode );
}
// -------------------------------------------------------------------------------- //
guMediaViewerJamendo::~guMediaViewerJamendo()
{
Unbind( wxEVT_MENU, &guMediaViewerJamendo::OnCoverDownloaded, this, ID_JAMENDO_COVER_DOWNLAODED );
Unbind( wxEVT_MENU, &guMediaViewerJamendo::OnUpdateFinished, this, ID_JAMENDO_UPDATE_FINISHED );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::LoadMediaDb( void )
{
guLogMessage( wxT( "LoadMediaDb... JAMENDO..." ) );
m_Db = new guJamendoLibrary( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId + wxT( "/guayadeque.db" ) );
m_Db->SetMediaViewer( this );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::OnConfigUpdated( wxCommandEvent &event )
{
guMediaViewer::OnConfigUpdated( event );
if( event.GetInt() & guPREFERENCE_PAGE_FLAG_JAMENDO )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_JAMENDO_NEED_UPGRADE, false, CONFIG_PATH_JAMENDO ) )
{
UpdateLibrary();
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::UpdateLibrary( void )
{
int GaugeId;
GaugeId = m_MainFrame->AddGauge( m_MediaCollection->m_Name );
if( m_UpdateThread )
{
m_UpdateThread->Pause();
m_UpdateThread->Delete();
}
m_UpdateThread = new guJamendoUpdateThread( this, guJAMENDO_ACTION_UPDATE, GaugeId );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::UpgradeLibrary( void )
{
int GaugeId;
GaugeId = m_MainFrame->AddGauge( m_MediaCollection->m_Name );
if( m_UpdateThread )
{
m_UpdateThread->Pause();
m_UpdateThread->Delete();
}
m_UpdateThread = new guJamendoUpdateThread( this, guJAMENDO_ACTION_UPGRADE, GaugeId );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
int Count;
if( tracks && ( Count = tracks->Count() ) )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
int AudioFormat = Config->ReadNum( CONFIG_KEY_JAMENDO_AUDIOFORMAT, 1, CONFIG_PATH_JAMENDO );
for( int Index = 0; Index < Count; Index++ )
{
guTrack * Track = &( * tracks )[ Index ];
Track->m_FileName = wxString::Format( guJAMENDO_FILE_STREAM_URL, Track->m_SongId );
Track->m_FileName += AudioFormat ? guJAMENDO_STREAM_FORMAT_OGG : guJAMENDO_STREAM_FORMAT_MP3;
Track->m_Type = guTRACK_TYPE_JAMENDO;
if( isdrag )
Track->m_FileName.Replace( wxT( "http://" ), wxT( "/" ) );
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::AddDownload( const int albumid, const bool iscover )
{
//guLogMessage( wxT( "Error... %i" ), 1000 / 0 );
wxMutexLocker Lock( m_DownloadThreadMutex );
if( !m_DownloadThread )
{
m_DownloadThread = new guJamendoDownloadThread( this );
if( !m_DownloadThread )
{
guLogMessage( wxT( "Could not create the jamendo download thread" ) );
return;
}
}
m_DownloadThread->AddAlbum( albumid, iscover );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::AddDownloads( const wxArrayInt &albumids, const bool iscover )
{
wxMutexLocker Lock( m_DownloadThreadMutex );
if( !m_DownloadThread )
{
m_DownloadThread = new guJamendoDownloadThread( this );
if( !m_DownloadThread )
{
guLogMessage( wxT( "Could not create the jamendo download thread" ) );
return;
}
}
m_DownloadThread->AddAlbums( albumids, iscover );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::OnCoverDownloaded( wxCommandEvent &event )
{
AlbumCoverChanged( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::EndUpdateThread( void )
{
m_UpdateThread = NULL;
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::EndDownloadThread( void )
{
wxMutexLocker Lock( m_DownloadThreadMutex );
m_DownloadThread = NULL;
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::OnUpdateFinished( wxCommandEvent &event )
{
EndUpdateThread();
LibraryUpdated();
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::DownloadAlbumCover( const int albumid )
{
AddDownload( albumid, true );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::CreateContextMenu( wxMenu * menu, const int windowid )
{
wxMenu * Menu = new wxMenu();
wxMenuItem * MenuItem;
int BaseCommand = GetBaseCommand();
if( ( windowid == guLIBRARY_ELEMENT_ALBUMS ) )
{
MenuItem = new wxMenuItem( menu, ID_JAMENDO_DOWNLOAD_DIRECT_ALBUM, _( "Download Albums" ), _( "Download the current selected album" ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_JAMENDO_DOWNLOAD_TORRENT_ALBUM, _( "Download Albums torrents" ), _( "Download the current selected album" ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
}
else if( ( windowid == guLIBRARY_ELEMENT_TRACKS ) )
{
MenuItem = new wxMenuItem( menu, ID_JAMENDO_DOWNLOAD_DIRECT_TRACK_ALBUM, _( "Download Albums" ), _( "Download the current selected album" ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( menu, ID_JAMENDO_DOWNLOAD_TORRENT_TRACK_ALBUM, _( "Download Albums torrents" ), _( "Download the current selected album" ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
}
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY, _( "Update" ), _( "Update the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY, _( "Rescan" ), _( "Rescan the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS, _( "Search Covers" ), _( "Search the collection missing covers" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_VIEW_PROPERTIES, _( "Properties" ), _( "Show collection properties" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
menu->AppendSeparator();
menu->AppendSubMenu( Menu, wxT( "Jamendo" ) );
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerJamendo::CreateLibraryView( void )
{
guLogMessage( wxT( "CreateLibraryView... Jamendo...") );
m_LibPanel = new guJamendoPanel( this, this );
m_LibPanel->SetBaseCommand( m_BaseCommand + 1 );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerJamendo::CreateAlbumBrowserView( void )
{
m_AlbumBrowser = new guJamendoAlbumBrowser( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerJamendo::CreateTreeView( void )
{
m_TreeViewPanel = new guJamendoTreePanel( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerJamendo::CreatePlayListView( void )
{
m_PlayListPanel = new guJamendoPlayListPanel( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
wxImage * guMediaViewerJamendo::GetAlbumCover( const int albumid, int &coverid,
wxString &coverpath, const wxString &artistname, const wxString &albumname )
{
wxImage * CoverImage = guMediaViewer::GetAlbumCover( albumid, coverid, coverpath, artistname, albumname );
if( CoverImage )
return CoverImage;
wxString CoverFile = guPATH_JAMENDO_COVERS + GetCoverName( albumid ) + wxT( ".jpg" );
if( wxFileExists( CoverFile ) )
{
wxImage * CoverImage = new wxImage( CoverFile, wxBITMAP_TYPE_JPEG );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
coverpath = CoverFile;
SetAlbumCover( albumid, guPATH_JAMENDO_COVERS, coverpath );
coverid = m_Db->GetAlbumCoverId( albumid );
return CoverImage;
}
delete CoverImage;
}
}
AddDownload( albumid );
return NULL;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewerJamendo::GetCoverName( const int albumid )
{
return wxString::Format( wxT( "%u" ), albumid );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::SelectAlbumCover( const int albumid )
{
guSelCoverFile * SelCoverFile = new guSelCoverFile( this, this, albumid );
if( SelCoverFile )
{
if( SelCoverFile->ShowModal() == wxID_OK )
{
wxString CoverFile = SelCoverFile->GetSelFile();
if( !CoverFile.IsEmpty() )
{
if( SetAlbumCover( albumid, guPATH_JAMENDO_COVERS, CoverFile ) )
{
if( SelCoverFile->EmbedToFiles() )
{
EmbedAlbumCover( albumid );
}
}
}
}
SelCoverFile->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::DownloadAlbums( const wxArrayInt &albums, const bool istorrent )
{
int Count = albums.Count();
if( Count )
{
if( istorrent )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxString TorrentCmd = Config->ReadStr( CONFIG_KEY_JAMENDO_TORRENT_COMMAND, wxEmptyString, CONFIG_PATH_JAMENDO );
if( TorrentCmd.IsEmpty() )
{
//OnEditSetup( event );
return;
}
AddDownloads( albums, false );
}
else
{
for( int Index = 0; Index < Count; Index++ )
{
guWebExecute( wxString::Format( guJAMENDO_DOWNLOAD_DIRECT, albums[ Index ] ) );
}
}
}
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerJamendo::FindMissingCover( const int albumid, const wxString &artistname, const wxString &albumname, const wxString &albumpath )
{
AddDownload( albumid, true );
return true;
}
// -------------------------------------------------------------------------------- //
void guMediaViewerJamendo::EditProperties( void )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_JAMENDO );
wxPostEvent( m_MainFrame, CmdEvent );
}
}
// -------------------------------------------------------------------------------- //
| 47,312
|
C++
|
.cpp
| 1,103
| 35.368994
| 171
| 0.529514
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,581
|
CoverEdit.cpp
|
anonbeat_guayadeque/src/ui/cover/CoverEdit.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CoverEdit.h"
#include "Amazon.h"
#include "Apple.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "CoverFetcher.h"
#include "CoverFrame.h"
//#include "Discogs.h"
#include "Google.h"
#include "Images.h"
#include "LastFMCovers.h"
#include "MainFrame.h"
#include "Utils.h"
#include "Yahoo.h"
#include <wx/arrimpl.cpp>
#include <wx/filedlg.h>
#include <wx/statline.h>
#define MAX_COVERLINKS_ITEMS 30
namespace Guayadeque {
enum guCOVER_SEARCH_ENGINE {
// guCOVER_SEARCH_ENGINE_GOOGLE = 0,
// guCOVER_SEARCH_ENGINE_AMAZON,
guCOVER_SEARCH_ENGINE_APPLE,
guCOVER_SEARCH_ENGINE_LASTFM,
// guCOVER_SEARCH_ENGINE_DISCOGS
// guCOVER_SEARCH_ENGINE_YAHOO
};
WX_DEFINE_OBJARRAY( guCoverImageArray )
// -------------------------------------------------------------------------------- //
guCoverEditor::guCoverEditor( wxWindow* parent, const wxString &Artist, const wxString &Album, const wxString &albumpath ) :
wxDialog( parent, wxID_ANY, _( "Cover Editor" ), wxDefaultPosition, wxSize( 520, 446 ), wxDEFAULT_DIALOG_STYLE )
{
m_AlbumPath = albumpath;
wxStaticText* ArtistStaticText;
wxStaticText* AlbumStaticText;
wxStaticText* FromStaticText;
wxStaticLine * TopStaticLine;
guConfig * Config = ( guConfig * ) guConfig::Get();
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer* MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* EditsSizer;
EditsSizer = new wxBoxSizer( wxHORIZONTAL );
ArtistStaticText = new wxStaticText( this, wxID_ANY, _( "Artist:" ), wxDefaultPosition, wxDefaultSize, 0 );
ArtistStaticText->Wrap( -1 );
EditsSizer->Add( ArtistStaticText, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
m_ArtistTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
EditsSizer->Add( m_ArtistTextCtrl, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
AlbumStaticText = new wxStaticText( this, wxID_ANY, _( "Album:" ), wxDefaultPosition, wxDefaultSize, 0 );
AlbumStaticText->Wrap( -1 );
EditsSizer->Add( AlbumStaticText, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
m_AlbumTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
EditsSizer->Add( m_AlbumTextCtrl, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
FromStaticText = new wxStaticText( this, wxID_ANY, _( "From:" ), wxDefaultPosition, wxDefaultSize, 0 );
FromStaticText->Wrap( -1 );
EditsSizer->Add( FromStaticText, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
wxString m_EngineChoiceChoices[] = {
//wxT( "Google" ),
//wxT( "Amazon" ),
wxT( "Apple" ),
wxT("Last.fm"),
//wxT( "Discogs" )
//wxT( "Yahoo" )
};
int m_EngineChoiceNChoices = sizeof( m_EngineChoiceChoices ) / sizeof( wxString );
m_EngineChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_EngineChoiceNChoices, m_EngineChoiceChoices, 0 );
EditsSizer->Add( m_EngineChoice, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
MainSizer->Add( EditsSizer, 0, wxEXPAND, 5 );
wxBoxSizer * TopButtonsSizer = new wxBoxSizer( wxHORIZONTAL );
m_EmbedToFilesChkBox = new wxCheckBox( this, wxID_ANY, _( "Embed into tracks" ), wxDefaultPosition, wxDefaultSize, 0 );
m_EmbedToFilesChkBox->SetValue( Config->ReadBool( CONFIG_KEY_GENERAL_EMBED_TO_FILES, false, CONFIG_PATH_GENERAL ) );
TopButtonsSizer->Add( m_EmbedToFilesChkBox, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 );
TopButtonsSizer->Add( 10, 10, wxEXPAND );
m_CoverSelectButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_download_covers ), wxDefaultPosition, wxSize( 32, 32 ), wxBU_AUTODRAW );
TopButtonsSizer->Add( m_CoverSelectButton, 0, wxALIGN_RIGHT | wxLEFT, 5 );
m_CoverDownloadButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_doc_save ), wxDefaultPosition, wxSize( 32, 32 ), wxBU_AUTODRAW );
TopButtonsSizer->Add( m_CoverDownloadButton, 0, wxALIGN_RIGHT | wxLEFT | wxRIGHT, 5 );
MainSizer->Add( TopButtonsSizer, 0, wxEXPAND, 5 );
TopStaticLine = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
MainSizer->Add( TopStaticLine, 0, wxEXPAND | wxALL, 5 );
wxBoxSizer * CoverSizer = new wxBoxSizer( wxHORIZONTAL );
CoverSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_PrevButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_left ), wxDefaultPosition, wxSize( 32, 96 ), wxBU_AUTODRAW );
CoverSizer->Add( m_PrevButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
int CoverFrame = Config->ReadNum( CONFIG_KEY_GENERAL_COVER_FRAME, guCOVERFRAME_DEFAULT, CONFIG_PATH_GENERAL );
wxImage DefaultCover( guImage( CoverFrame ? guIMAGE_INDEX_blank_cd_cover : guIMAGE_INDEX_no_cover ) );
if( !CoverFrame ) DefaultCover.Rescale( 250, 250, wxIMAGE_QUALITY_HIGH );
m_CoverBitmap = new wxStaticBitmap( this, wxID_ANY, DefaultCover, wxDefaultPosition, wxSize( -1,-1 ), 0 );
CoverSizer->Add( m_CoverBitmap, 0, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5 );
m_NextButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_right ), wxDefaultPosition, wxSize( 32, 96 ), wxBU_AUTODRAW );
CoverSizer->Add( m_NextButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
CoverSizer->Add( 0, 0, 1, wxEXPAND, 5 );
MainSizer->Add( CoverSizer, 1, wxEXPAND, 5 );
m_SizeSizer = new wxBoxSizer( wxVERTICAL );
m_SizeStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_SizeStaticText->Wrap( -1 );
m_SizeSizer->Add( m_SizeStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 );
MainSizer->Add( m_SizeSizer, 0, wxEXPAND, 5 );
wxBoxSizer* GaugeSizer = new wxBoxSizer( wxHORIZONTAL );
m_Gauge = new guAutoPulseGauge( this, wxID_ANY, MAX_COVERLINKS_ITEMS, wxDefaultPosition, wxSize( -1,7 ), wxGA_HORIZONTAL );
m_Gauge->SetValue( 5 );
GaugeSizer->Add( m_Gauge, 1, wxEXPAND|wxALL, 5 );
m_InfoTextCtrl = new wxStaticText( this, wxID_ANY, wxT("00/00"), wxDefaultPosition, wxDefaultSize, 0 );
m_InfoTextCtrl->Wrap( -1 );
GaugeSizer->Add( m_InfoTextCtrl, 0, wxRIGHT, 5 );
MainSizer->Add( GaugeSizer, 0, wxEXPAND, 5 );
wxStdDialogButtonSizer * ButtonsSizer = new wxStdDialogButtonSizer();
wxButton * ButtonsSizerOK = new wxButton( this, wxID_OK );
ButtonsSizer->AddButton( ButtonsSizerOK );
wxButton * ButtonsSizerCancel = new wxButton( this, wxID_CANCEL );
ButtonsSizer->AddButton( ButtonsSizerCancel );
ButtonsSizer->SetAffirmativeButton( ButtonsSizerOK );
ButtonsSizer->SetCancelButton( ButtonsSizerCancel );
ButtonsSizer->Realize();
MainSizer->Add( ButtonsSizer, 0, wxEXPAND|wxALIGN_BOTTOM|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
ButtonsSizerOK->SetDefault();
m_ArtistTextCtrl->SetValue( Artist );
m_AlbumTextCtrl->SetValue( Album );
m_CurrentImage = 0;
m_EngineIndex = Config->ReadNum( CONFIG_KEY_GENERAL_COVER_SEARCH_ENGINE, 0, CONFIG_PATH_GENERAL );
if( m_EngineIndex >= ( int ) m_EngineChoice->GetCount() )
m_EngineIndex = 0;
m_EngineChoice->SetSelection( m_EngineIndex );
// Bind Events
m_ArtistTextCtrl->Bind( wxEVT_TEXT_ENTER, &guCoverEditor::OnTextCtrlEnter, this );
m_AlbumTextCtrl->Bind( wxEVT_TEXT_ENTER, &guCoverEditor::OnTextCtrlEnter, this );
m_EngineChoice->Bind( wxEVT_CHOICE, &guCoverEditor::OnEngineChanged, this );
m_CoverBitmap->Bind( wxEVT_LEFT_DCLICK, &guCoverEditor::OnCoverLeftDClick, this );
m_CoverBitmap->Bind( wxEVT_LEFT_DOWN, &guCoverEditor::OnCoverLeftClick, this );
Bind( wxEVT_MOUSEWHEEL, &guCoverEditor::OnMouseWheel, this );
m_PrevButton->Bind( wxEVT_BUTTON, &guCoverEditor::OnPrevButtonClick, this );
m_NextButton->Bind( wxEVT_BUTTON, &guCoverEditor::OnNextButtonClick, this );
m_CoverSelectButton->Bind( wxEVT_BUTTON, &guCoverEditor::OnCoverSelectClick, this );
m_CoverDownloadButton->Bind( wxEVT_BUTTON, &guCoverEditor::OnCoverDownloadClick, this );
Bind( wxEVT_MENU, &guCoverEditor::OnAddCoverImage, this, ID_COVEREDITOR_ADDCOVERIMAGE );
Bind( wxEVT_MENU, &guCoverEditor::OnDownloadedLinks, this, ID_COVEREDITOR_DOWNLOADEDLINKS );
m_DownloadCoversThread = new guFetchCoverLinksThread( this, Artist.c_str(), Album.c_str(), m_EngineIndex );
m_PrevButton->Disable();
m_NextButton->Disable();
m_ArtistTextCtrl->SetFocus();
}
// -------------------------------------------------------------------------------- //
guCoverEditor::~guCoverEditor()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteNum( CONFIG_KEY_GENERAL_COVER_SEARCH_ENGINE, m_EngineChoice->GetSelection(), CONFIG_PATH_GENERAL );
Config->WriteBool( CONFIG_KEY_GENERAL_EMBED_TO_FILES, m_EmbedToFilesChkBox->GetValue(), CONFIG_PATH_GENERAL );
m_DownloadThreadMutex.Lock();
int count = m_DownloadThreads.Count();
for( int index = 0; index < count; index++ )
{
guDownloadCoverThread * DownThread = ( guDownloadCoverThread * ) m_DownloadThreads[ index ];
if( DownThread )
{
DownThread->Pause();
DownThread->Delete();
}
m_DownloadThreads[ index ] = NULL;
}
m_DownloadThreadMutex.Unlock();
if( m_DownloadCoversThread )
{
m_DownloadCoversThread->Pause();
m_DownloadCoversThread->Delete();
}
// Unbind Events
m_ArtistTextCtrl->Unbind( wxEVT_TEXT_ENTER, &guCoverEditor::OnTextCtrlEnter, this );
m_AlbumTextCtrl->Unbind( wxEVT_TEXT_ENTER, &guCoverEditor::OnTextCtrlEnter, this );
m_EngineChoice->Unbind( wxEVT_CHOICE, &guCoverEditor::OnEngineChanged, this );
m_CoverBitmap->Unbind( wxEVT_LEFT_DCLICK, &guCoverEditor::OnCoverLeftDClick, this );
m_CoverBitmap->Unbind( wxEVT_LEFT_DOWN, &guCoverEditor::OnCoverLeftClick, this );
Unbind( wxEVT_MOUSEWHEEL, &guCoverEditor::OnMouseWheel, this );
m_PrevButton->Unbind( wxEVT_BUTTON, &guCoverEditor::OnPrevButtonClick, this );
m_NextButton->Unbind( wxEVT_BUTTON, &guCoverEditor::OnNextButtonClick, this );
m_CoverSelectButton->Unbind( wxEVT_BUTTON, &guCoverEditor::OnCoverSelectClick, this );
m_CoverDownloadButton->Unbind( wxEVT_BUTTON, &guCoverEditor::OnCoverDownloadClick, this );
Unbind( wxEVT_MENU, &guCoverEditor::OnAddCoverImage, this, ID_COVEREDITOR_ADDCOVERIMAGE );
Unbind( wxEVT_MENU, &guCoverEditor::OnDownloadedLinks, this, ID_COVEREDITOR_DOWNLOADEDLINKS );
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::EndDownloadLinksThread( void )
{
m_DownloadThreadMutex.Lock();
if( !m_DownloadThreads.Count() )
{
if( m_Gauge->IsPulsing() )
{
m_Gauge->StopPulse( MAX_COVERLINKS_ITEMS, MAX_COVERLINKS_ITEMS );
}
else
{
m_Gauge->SetValue( MAX_COVERLINKS_ITEMS );
}
}
m_DownloadThreadMutex.Unlock();
//m_Gauge->SetValue( 0 );
//guLogMessage( wxT( "EndDownloadThread called" ) );
m_DownloadCoversThread = NULL;
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnDownloadedLinks( wxCommandEvent &event )
{
EndDownloadLinksThread();
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::EndDownloadCoverThread( guDownloadCoverThread * DownloadCoverThread )
{
if( m_Gauge->IsPulsing() )
{
m_Gauge->StopPulse( MAX_COVERLINKS_ITEMS, 1 );
}
else
{
m_Gauge->SetValue( wxMin( m_Gauge->GetValue() + 1, MAX_COVERLINKS_ITEMS ) );
}
m_DownloadThreadMutex.Lock();
m_DownloadThreads.Remove( DownloadCoverThread );
m_DownloadThreadMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnPrevButtonClick( wxCommandEvent& event )
{
if( m_CurrentImage )
{
m_CurrentImage--;
if( !m_NextButton->IsEnabled() )
m_NextButton->Enable();
if( !m_CurrentImage )
m_PrevButton->Disable();
UpdateCoverBitmap();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnNextButtonClick( wxCommandEvent& event )
{
if( m_CurrentImage < ( int ) ( m_AlbumCovers.Count() - 1 ) )
{
m_CurrentImage++;
if( m_CurrentImage == ( int ) m_AlbumCovers.Count() - 1 )
m_NextButton->Disable();
if( !m_PrevButton->IsEnabled() )
m_PrevButton->Enable();
UpdateCoverBitmap();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnMouseWheel( wxMouseEvent &event )
{
int Rotation = event.GetWheelRotation() / event.GetWheelDelta() * -1;
int NewPos = m_CurrentImage + Rotation;
//guLogMessage( wxT( "MouseWheel %i => %i" ), m_CurrentImage, NewPos );
NewPos = wxMax( 0, wxMin( NewPos, ( int ) m_AlbumCovers.Count() - 1 ) );
if( NewPos != m_CurrentImage )
{
m_CurrentImage = NewPos;
m_NextButton->Enable( m_CurrentImage < ( int ) m_AlbumCovers.Count() - 1 );
m_PrevButton->Enable( m_CurrentImage );
UpdateCoverBitmap();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnAddCoverImage( wxCommandEvent &event )
{
m_DownloadEventsMutex.Lock();
guCoverImage * Image = ( guCoverImage * ) event.GetClientData();
if( Image )
{
if( Image->m_SizeStr.IsEmpty() )
Image->m_SizeStr = wxString::Format( wxT( "%ux%u" ), Image->m_Image->GetWidth(), Image->m_Image->GetHeight() );
m_AlbumCovers.Add( Image );
// When it is the first show the image.
if( m_AlbumCovers.Count() == 1 )
UpdateCoverBitmap();
if( ( m_CurrentImage < ( int ) ( m_AlbumCovers.Count() - 1 ) ) && !m_NextButton->IsEnabled() )
m_NextButton->Enable();
m_InfoTextCtrl->SetLabel( wxString::Format( wxT( "%02u/%02lu" ), m_CurrentImage + 1, m_AlbumCovers.Count() ) );
//guLogMessage( wxT( "CurImg: %u Total:%lu" ), m_CurrentImage + 1, m_AlbumCovers.Count() );
}
if( event.GetClientObject() )
EndDownloadCoverThread( ( guDownloadCoverThread * ) event.GetClientObject() );
m_DownloadEventsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::UpdateCoverBitmap( void )
{
m_InfoTextCtrl->SetLabel( wxString::Format( wxT( "%02u/%02lu" ), m_AlbumCovers.Count() ? m_CurrentImage + 1 : 0, m_AlbumCovers.Count() ) );
guConfig * Config = ( guConfig * ) guConfig::Get();
int CoverFrame = Config->ReadNum( CONFIG_KEY_GENERAL_COVER_FRAME, guCOVERFRAME_DEFAULT, CONFIG_PATH_GENERAL );
if( CoverFrame == guCOVERFRAME_DEFAULT )
{
wxBitmap * BlankCD = new wxBitmap( guImage( guIMAGE_INDEX_blank_cd_cover ) );
if( BlankCD )
{
if( BlankCD->IsOk() )
{
if( m_AlbumCovers.Count() && m_AlbumCovers[ m_CurrentImage ].m_Image )
{
wxImage CoverImage = m_AlbumCovers[ m_CurrentImage ].m_Image->Copy();
// 38,6
wxMemoryDC MemDC;
MemDC.SelectObject( * BlankCD );
CoverImage.Rescale( 250, 250, wxIMAGE_QUALITY_HIGH );
MemDC.DrawBitmap( wxBitmap( CoverImage ), 34, 4, false );
// Update the Size label
m_SizeStaticText->SetLabel( m_AlbumCovers[ m_CurrentImage ].m_SizeStr );
}
else
{
m_SizeStaticText->SetLabel( wxEmptyString );
}
m_SizeSizer->Layout();
m_CoverBitmap->SetBitmap( * BlankCD );
m_CoverBitmap->Refresh();
}
delete BlankCD;
}
}
else
{
wxImage CoverImage;
if( m_AlbumCovers.Count() && m_AlbumCovers[ m_CurrentImage ].m_Image )
{
CoverImage = m_AlbumCovers[ m_CurrentImage ].m_Image->Copy();
// Update the Size label
m_SizeStaticText->SetLabel( m_AlbumCovers[ m_CurrentImage ].m_SizeStr );
}
else
{
CoverImage = guImage( guIMAGE_INDEX_no_cover );
m_SizeStaticText->SetLabel( wxEmptyString );
}
CoverImage.Rescale( 250, 250, wxIMAGE_QUALITY_HIGH );
m_SizeSizer->Layout();
m_CoverBitmap->SetBitmap( CoverImage );
m_CoverBitmap->Refresh();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnCoverLeftDClick( wxMouseEvent &event )
{
if( event.m_x >= 75 && event.m_x <= 225 )
EndModal( wxID_OK );
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnCoverLeftClick( wxMouseEvent &event )
{
wxCommandEvent CmdEvent;
if( event.m_x < 75 )
{
OnPrevButtonClick( CmdEvent );
}
else if( event.m_x > 225 )
{
OnNextButtonClick( CmdEvent );
}
//guLogMessage( wxT( "%i %i" ), event.m_x, event.m_y );
event.Skip();
}
// -------------------------------------------------------------------------------- //
wxString guCoverEditor::GetSelectedCoverUrl( void )
{
if( m_AlbumCovers.Count() )
return m_AlbumCovers[ m_CurrentImage ].m_Link;
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
wxImage * guCoverEditor::GetSelectedCoverImage( void )
{
if( m_AlbumCovers.Count() )
return m_AlbumCovers[ m_CurrentImage ].m_Image;
return NULL;
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnTextCtrlEnter( wxCommandEvent& event )
{
m_DownloadThreadMutex.Lock();
int count = m_DownloadThreads.Count();
for( int index = 0; index < count; index++ )
{
guDownloadCoverThread * DownThread = ( guDownloadCoverThread * ) m_DownloadThreads[ index ];
if( DownThread )
{
DownThread->Pause();
DownThread->Delete();
}
}
m_DownloadThreads.Empty();
m_DownloadThreadMutex.Unlock();
// If Thread still running delete it
if( m_DownloadCoversThread )
{
m_DownloadCoversThread->Pause();
m_DownloadCoversThread->Delete();
}
// Empty already downloaded covers
m_AlbumCovers.Empty();
// Reset to the 1st Image
m_CurrentImage = 0;
// Set blank Cover Bitmap
UpdateCoverBitmap();
m_Gauge->StartPulse();
// Start again the cover fetcher thread
m_DownloadCoversThread = new guFetchCoverLinksThread( this,
m_ArtistTextCtrl->GetValue().c_str(),
m_AlbumTextCtrl->GetValue().c_str(), m_EngineIndex );
// Disable buttons till one cover is downloaded
m_PrevButton->Disable();
m_NextButton->Disable();
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnEngineChanged( wxCommandEvent& event )
{
if( m_EngineIndex != m_EngineChoice->GetSelection() )
{
m_DownloadThreadMutex.Lock();
int count = m_DownloadThreads.Count();
for( int index = 0; index < count; index++ )
{
guDownloadCoverThread * DownThread = ( guDownloadCoverThread * ) m_DownloadThreads[ index ];
if( DownThread )
{
DownThread->Pause();
DownThread->Delete();
}
}
m_DownloadThreads.Empty();
m_DownloadThreadMutex.Unlock();
// If Thread still running delete it
if( m_DownloadCoversThread )
{
m_DownloadCoversThread->Pause();
m_DownloadCoversThread->Delete();
}
// Empty already downloaded covers
m_AlbumCovers.Empty();
// Reset to the 1st Image
m_CurrentImage = 0;
// Set blank Cover Bitmap
UpdateCoverBitmap();
m_Gauge->StartPulse();
m_EngineIndex = m_EngineChoice->GetSelection();
// Start again the cover fetcher thread
m_DownloadCoversThread = new guFetchCoverLinksThread( this,
m_ArtistTextCtrl->GetValue().c_str(),
m_AlbumTextCtrl->GetValue().c_str(), m_EngineIndex );
// Disable buttons till one cover is downloaded
m_PrevButton->Disable();
m_NextButton->Disable();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnCoverSelectClick( wxCommandEvent & )
{
wxFileDialog * FileDialog = new wxFileDialog( this, _( "Select the cover filename" ),
m_AlbumPath, "", wxT( "*.jpg;*.JPG;*.jpeg;*.JPEG;*.png;*,PNG" ),
wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_PREVIEW );
if( FileDialog )
{
if( FileDialog->ShowModal() == wxID_OK )
{
wxString CoverFile = FileDialog->GetPath();
if( !CoverFile.IsEmpty() )
{
wxImage * CoverImage = new wxImage( CoverFile );
if( CoverImage->IsOk() )
{
wxCommandEvent event( wxEVT_MENU, ID_COVEREDITOR_ADDCOVERIMAGE );
event.SetClientData( new guCoverImage( CoverFile, "", CoverImage ) );
OnAddCoverImage( event );
}
}
}
FileDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guCoverEditor::OnCoverDownloadClick( wxCommandEvent & )
{
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, "Url:",
_( "Cover Url" ), wxEmptyString );
if( EntryDialog )
{
if( EntryDialog->ShowModal() == wxID_OK )
{
wxString CoverUrl = EntryDialog->GetValue();
if( !CoverUrl.IsEmpty() )
{
wxBitmapType CoverType;
wxImage * CoverImage = guGetRemoteImage( CoverUrl, CoverType );
if( CoverImage )
{
wxCommandEvent event( wxEVT_MENU, ID_COVEREDITOR_ADDCOVERIMAGE );
event.SetClientData( new guCoverImage( CoverUrl, "", CoverImage ) );
OnAddCoverImage( event );
}
}
}
EntryDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
// guFetchCoverLinksThread
// -------------------------------------------------------------------------------- //
guFetchCoverLinksThread::guFetchCoverLinksThread( guCoverEditor * owner,
const wxChar * artist, const wxChar * album, int engineindex ) :
wxThread()
{
m_CoverEditor = owner;
m_CoverFetcher = NULL;
// m_Artist = wxString( artist );
// m_Album = wxString( album );
m_EngineIndex = engineindex;
m_LastDownload = 0;
m_CurrentPage = 0;
// if( m_EngineIndex == guCOVER_SEARCH_ENGINE_GOOGLE )
// {
// m_CoverFetcher = ( guCoverFetcher * ) new guGoogleCoverFetcher( this, &m_CoverLinks, artist, album );
// }
// else if( m_EngineIndex == guCOVER_SEARCH_ENGINE_AMAZON )
// if( m_EngineIndex == guCOVER_SEARCH_ENGINE_AMAZON )
// {
// m_CoverFetcher = ( guCoverFetcher * ) new guAmazonCoverFetcher( this, &m_CoverLinks, artist, album );
// }
// else if( m_EngineIndex == guCOVER_SEARCH_ENGINE_APPLE )
if( m_EngineIndex == guCOVER_SEARCH_ENGINE_APPLE )
{
m_CoverFetcher = ( guCoverFetcher * ) new guAppleCoverFetcher( this, &m_CoverLinks, artist, album );
}
else if( m_EngineIndex == guCOVER_SEARCH_ENGINE_LASTFM )
{
m_CoverFetcher = ( guCoverFetcher * ) new guLastFMCoverFetcher( this, &m_CoverLinks, artist, album );
}
// else if( m_EngineIndex == guCOVER_SEARCH_ENGINE_DISCOGS )
// {
// m_CoverFetcher = ( guCoverFetcher * ) new guDiscogsCoverFetcher( this, &m_CoverLinks, artist, album );
// }
// else if( m_EngineIndex == guCOVER_SEARCH_ENGINE_YAHOO )
// {
// m_CoverFetcher = ( guCoverFetcher * ) new guYahooCoverFetcher( this, &m_CoverLinks, artist, album );
// }
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guFetchCoverLinksThread::~guFetchCoverLinksThread()
{
if( !TestDestroy() )
{
wxCommandEvent event( wxEVT_MENU, ID_COVEREDITOR_DOWNLOADEDLINKS );
event.SetClientObject( ( wxClientData * ) this );
wxPostEvent( m_CoverEditor, event );
}
}
// -------------------------------------------------------------------------------- //
guFetchCoverLinksThread::ExitCode guFetchCoverLinksThread::Entry()
{
bool NoMorePics = false;
if( m_CoverFetcher )
{
while( !TestDestroy() )
{
if( m_LastDownload < ( int ) m_CoverLinks.Count() )
{
m_CoverEditor->m_DownloadThreadMutex.Lock();
if( !TestDestroy() )
{
guDownloadCoverThread * DownloadThread = new guDownloadCoverThread( m_CoverEditor,
&m_CoverLinks[ m_LastDownload ] );
if( !DownloadThread )
{
guLogError( wxT( "Could not create the download covers thread" ) );
}
}
m_CoverEditor->m_DownloadThreadMutex.Unlock();
m_LastDownload++;
Sleep( 20 );
}
else
{
if( NoMorePics )
break;
if( m_CoverLinks.Count() > MAX_COVERLINKS_ITEMS )
break;
if( !m_CoverFetcher->AddCoverLinks( m_CurrentPage ) )
{
NoMorePics = true;
if( m_LastDownload < ( int ) m_CoverLinks.Count() )
{
continue;
}
break;
}
m_CurrentPage++;
}
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guDownloadCoverThread
// -------------------------------------------------------------------------------- //
guDownloadCoverThread::guDownloadCoverThread( guCoverEditor * Owner, const wxArrayString * CoverInfo ) :
wxThread()
{
m_CoverEditor = Owner;
m_UrlStr = wxString( ( * CoverInfo )[ GUCOVERINFO_LINK ].c_str() );
m_SizeStr = wxString( ( * CoverInfo )[ GUCOVERINFO_SIZE ].c_str() );
//guLogMessage( wxT( "Link : %s (%s)" ), UrlStr.c_str(), SizeStr.c_str() );
m_CoverEditor->m_DownloadThreads.Add( this );
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guDownloadCoverThread::~guDownloadCoverThread()
{
}
// -------------------------------------------------------------------------------- //
guDownloadCoverThread::ExitCode guDownloadCoverThread::Entry()
{
wxBitmapType ImageType;
guCoverImage * CoverImage = NULL;
wxImage * Image = guGetRemoteImage( m_UrlStr, ImageType );
if( Image )
{
if( !TestDestroy() )
{
CoverImage = new guCoverImage( m_UrlStr, m_SizeStr, Image );
}
else
{
//guLogWarning( wxT( "Could not load image from the net index %u." ), LastDownload );
delete Image;
}
}
if( !TestDestroy() )
{
//guLogMessage( wxT( "Done: '%s'" ), m_UrlStr.c_str() );
//m_CoverEditor->m_DownloadEventsMutex.Lock();
wxCommandEvent event( wxEVT_MENU, ID_COVEREDITOR_ADDCOVERIMAGE );
event.SetClientObject( ( wxClientData * ) this );
event.SetClientData( CoverImage );
wxPostEvent( m_CoverEditor, event );
//m_CoverEditor->m_DownloadEventsMutex.Unlock();
}
else
{
if( CoverImage )
delete CoverImage;
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 29,849
|
C++
|
.cpp
| 682
| 36.740469
| 157
| 0.584851
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,582
|
SelCoverFile.cpp
|
anonbeat_guayadeque/src/ui/cover/SelCoverFile.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "SelCoverFile.h"
#include "Config.h"
#include "EventCommandIds.h"
#include "MediaViewer.h"
#include <wx/filedlg.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guSelCoverFile::guSelCoverFile( wxWindow * parent, guMediaViewer * mediaviewer, const int albumid ) :
wxDialog( parent, wxID_ANY, _( "Select Cover File" ), wxDefaultPosition, wxSize( 400, 132 ), wxDEFAULT_DIALOG_STYLE )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
if( albumid != wxNOT_FOUND )
{
wxString AlbumName;
wxString ArtistName;
if( !m_Db->GetAlbumInfo( albumid, &AlbumName, &ArtistName, &m_AlbumPath ) )
{
wxMessageBox( _( "Could not find the Album in the songs library.\n"\
"You should update the library." ), _( "Error" ), wxICON_ERROR | wxOK );
}
}
guConfig * Config = ( guConfig * ) guConfig::Get();
// GUI
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer * ControlsSizer;
ControlsSizer = new wxBoxSizer( wxHORIZONTAL );
wxStaticText * CoverLabel = new wxStaticText( this, wxID_ANY, _( "Cover:" ), wxDefaultPosition, wxDefaultSize, 0 );
CoverLabel->Wrap( -1 );
ControlsSizer->Add( CoverLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_FileLink = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
ControlsSizer->Add( m_FileLink, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );
m_SelFileBtn = new wxButton( this, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 25,-1 ), 0 );
ControlsSizer->Add( m_SelFileBtn, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 );
MainSizer->Add( ControlsSizer, 1, wxEXPAND, 5 );
m_EmbedToFilesChkBox = new wxCheckBox( this, wxID_ANY, _( "Embed into tracks" ), wxDefaultPosition, wxDefaultSize, 0 );
m_EmbedToFilesChkBox->SetValue( Config->ReadBool( CONFIG_KEY_GENERAL_EMBED_TO_FILES, false, CONFIG_PATH_GENERAL ) );
MainSizer->Add( m_EmbedToFilesChkBox, 0, wxRIGHT|wxLEFT, 5 );
wxStdDialogButtonSizer * StdBtnSizer = new wxStdDialogButtonSizer();
m_StdBtnOk = new wxButton( this, wxID_OK );
m_StdBtnOk->Enable( false );
StdBtnSizer->AddButton( m_StdBtnOk );
wxButton * StdBtnSizerCancel = new wxButton( this, wxID_CANCEL );
StdBtnSizer->AddButton( StdBtnSizerCancel );
StdBtnSizer->SetAffirmativeButton( m_StdBtnOk );
StdBtnSizer->SetCancelButton( StdBtnSizerCancel );
StdBtnSizer->Realize();
MainSizer->Add( StdBtnSizer, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
m_StdBtnOk->SetDefault();
m_SelFileBtn->Bind( wxEVT_BUTTON, &guSelCoverFile::OnSelFileClicked, this );
m_FileLink->Bind( wxEVT_TEXT, &guSelCoverFile::OnPathChanged, this );
Bind( wxEVT_MENU, &guSelCoverFile::OnCoverFinish, this, ID_SELCOVERDIALOG_FINISH );
m_FileLink->SetFocus();
}
// -------------------------------------------------------------------------------- //
guSelCoverFile::~guSelCoverFile()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteBool( CONFIG_KEY_GENERAL_EMBED_TO_FILES, m_EmbedToFilesChkBox->GetValue(), CONFIG_PATH_GENERAL );
m_SelFileBtn->Unbind( wxEVT_BUTTON, &guSelCoverFile::OnSelFileClicked, this );
m_FileLink->Unbind( wxEVT_TEXT, &guSelCoverFile::OnPathChanged, this );
Unbind( wxEVT_MENU, &guSelCoverFile::OnCoverFinish, this, ID_SELCOVERDIALOG_FINISH );
}
// -------------------------------------------------------------------------------- //
void guSelCoverFile::OnSelFileClicked( wxCommandEvent& event )
{
wxString CoverName = m_MediaViewer->CoverName();
if( CoverName.IsEmpty() )
{
CoverName = wxT( "cover" );
}
CoverName += wxT( ".jpg " );
wxFileDialog * FileDialog = new wxFileDialog( this, _( "Select the cover filename" ),
m_AlbumPath, CoverName, wxT( "*.jpg;*.JPG;*.jpeg;*.JPEG;*.png;*,PNG" ),
wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_PREVIEW );
if( FileDialog )
{
if( FileDialog->ShowModal() == wxID_OK )
{
m_FileLink->SetValue( FileDialog->GetPath() );
wxCommandEvent event( wxEVT_MENU, ID_SELCOVERDIALOG_FINISH );
AddPendingEvent( event );
}
FileDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guSelCoverFile::OnCoverFinish( wxCommandEvent& event )
{
EndModal( wxID_OK );
}
// -------------------------------------------------------------------------------- //
wxString guSelCoverFile::GetSelFile( void )
{
return m_FileLink->GetValue();
}
// -------------------------------------------------------------------------------- //
void guSelCoverFile::OnPathChanged( wxCommandEvent &event )
{
m_StdBtnOk->Enable( !event.GetString().IsEmpty() );
}
}
// -------------------------------------------------------------------------------- //
| 6,051
|
C++
|
.cpp
| 128
| 43.546875
| 121
| 0.611168
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,583
|
Google.cpp
|
anonbeat_guayadeque/src/ui/cover/Google.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Google.h"
#include "CoverEdit.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/statline.h>
#include <wx/html/htmlpars.h>
namespace Guayadeque {
//#define GOOGLE_IMAGES_SEARCH_URL wxT( "http://images.google.com/images?imgsz=large|xlarge&q=%s&start=%u" )
//#define GOOGLE_IMAGES_SEARCH_URL wxT( "http://images.google.com/images?&q=%s&sout=1&start=%u" )
#define GOOGLE_IMAGES_SEARCH_URL wxT( "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s&rsz=8&start=%d" )
#define GOOGLE_COVERS_PER_PAGE 8
// -------------------------------------------------------------------------------- //
guGoogleCoverFetcher::guGoogleCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
void guGoogleCoverFetcher::ExtractImageInfo( const wxString &content )
{
//guLogMessage( wxT( "ExtractImageInfo: '%s'" ), content.c_str() );
wxArrayString CurImageInfo;
CurImageInfo.Add( ExtractString( content, wxT( "\"url\":\"" ), wxT( "\",\"" ) ) );
wxString ImgInfo = ExtractString( content, wxT( "\"width\":\"" ), wxT( "\",\"" ) );
if( !ImgInfo.IsEmpty() )
ImgInfo += wxT( " x " ) + ExtractString( content, wxT( "\"height\":\"" ), wxT( "\",\"" ) );
CurImageInfo.Add( ImgInfo );
m_CoverLinks->Add( CurImageInfo );
}
// -------------------------------------------------------------------------------- //
int guGoogleCoverFetcher::ExtractImagesInfo( wxString &content, int count )
{
int ImageIndex = 0;
while( !m_MainThread->TestDestroy() )
{
//guLogMessage( wxT( "%s\n" ), content.c_str() );
int FindPos = content.Find( wxT( "{\"GsearchResultClass\":" ) );
if( FindPos == wxNOT_FOUND )
{
break;
}
content = content.Mid( FindPos );
FindPos = content.Find( wxT( "}," ) );
if( FindPos == wxNOT_FOUND )
break;
ExtractImageInfo( content.Mid( 0, FindPos + 1 ) );
ImageIndex++;
if( ImageIndex > count )
break;
content = content.Mid( FindPos + 1 );
if( content.IsEmpty() )
break;
}
return ( ImageIndex == GOOGLE_COVERS_PER_PAGE ) ? ImageIndex : 0;
}
// -------------------------------------------------------------------------------- //
int guGoogleCoverFetcher::AddCoverLinks( int pagenum )
{
wxString SearchString = wxString::Format( wxT( "\"%s\" \"%s\"" ), m_Artist.c_str(), m_Album.c_str() );
//guLogMessage( wxT( "URL: %u %s" ), m_CurrentPage, m_SearchString.c_str() );
wxString SearchUrl = wxString::Format( GOOGLE_IMAGES_SEARCH_URL, guURLEncode( SearchString ).c_str(), ( pagenum * GOOGLE_COVERS_PER_PAGE ) );
//guLogMessage( wxT( "URL: %u %s" ), pagenum, SearchUrl.c_str() );
if( !m_MainThread->TestDestroy() )
{
wxString Content = GetUrlContent( SearchUrl );
if( Content.Length() )
{
if( !m_MainThread->TestDestroy() )
{
//guLogMessage( wxT( "Google:====>>>>\n%s\n<<<<====" ), Content.c_str() );
return ExtractImagesInfo( Content, GOOGLE_COVERS_PER_PAGE );
}
}
else
{
guLogError( wxT( "Could not get the remote data from connection" ) );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 4,662
|
C++
|
.cpp
| 103
| 40.07767
| 145
| 0.544894
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,584
|
CoverFrame.cpp
|
anonbeat_guayadeque/src/ui/cover/CoverFrame.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CoverFrame.h"
#include "Images.h"
#include "TagInfo.h"
#include "Utils.h"
#include "Config.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guCoverFrame::guCoverFrame( wxWindow * parent, wxWindowID id, const wxString & title, const wxPoint & pos, const wxSize & size, long style ) :
wxFrame( parent, id, title, pos, size, style | wxNO_BORDER | wxFRAME_NO_TASKBAR )
{
m_CapturedMouse = false;
m_AutoCloseTimer = new wxTimer( this );
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * CoverSizer;
CoverSizer = new wxBoxSizer( wxVERTICAL );
m_CoverBitmap = new wxStaticBitmap( this, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize( -1,-1 ), 0 );
CoverSizer->Add( m_CoverBitmap, 1, wxALL|wxEXPAND, 0 );
SetSizer( CoverSizer );
Layout();
m_AutoCloseTimer->Start( 1000, wxTIMER_ONE_SHOT );
Bind( wxEVT_ACTIVATE, &guCoverFrame::CoverFrameActivate, this );
Bind( wxEVT_LEFT_DOWN, &guCoverFrame::OnClick, this );
Bind( wxEVT_RIGHT_DOWN, &guCoverFrame::OnClick, this );
Bind( wxEVT_MOUSEWHEEL, &guCoverFrame::OnClick, this );
m_CoverBitmap->Bind( wxEVT_MOTION, &guCoverFrame::OnMouse, this );
Bind( wxEVT_MOTION, &guCoverFrame::OnMouse, this );
Bind( wxEVT_MOUSE_CAPTURE_LOST, &guCoverFrame::OnCaptureLost, this );
Bind( wxEVT_TIMER, &guCoverFrame::OnTimer, this );
}
// -------------------------------------------------------------------------------- //
guCoverFrame::~guCoverFrame()
{
if( m_CapturedMouse )
ReleaseMouse();
if( m_AutoCloseTimer )
delete m_AutoCloseTimer;
Unbind( wxEVT_ACTIVATE, &guCoverFrame::CoverFrameActivate, this );
Unbind( wxEVT_LEFT_DOWN, &guCoverFrame::OnClick, this );
Unbind( wxEVT_RIGHT_DOWN, &guCoverFrame::OnClick, this );
Unbind( wxEVT_MOUSEWHEEL, &guCoverFrame::OnClick, this );
m_CoverBitmap->Unbind( wxEVT_MOTION, &guCoverFrame::OnMouse, this );
Unbind( wxEVT_MOTION, &guCoverFrame::OnMouse, this );
Unbind( wxEVT_MOUSE_CAPTURE_LOST, &guCoverFrame::OnCaptureLost, this );
Unbind( wxEVT_TIMER, &guCoverFrame::OnTimer, this );
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::OnTimer( wxTimerEvent &event )
{
int MouseX, MouseY;
wxGetMousePosition( &MouseX, &MouseY );
wxRect WinRect = m_CoverBitmap->GetScreenRect();
if( !WinRect.Contains( MouseX, MouseY ) )
{
Close();
}
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::OnClick( wxMouseEvent &event )
{
Close();
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::SetBitmap( const guSongCoverType CoverType, const wxString &CoverPath )
{
wxImage CoverImage;
if( CoverType == GU_SONGCOVER_ID3TAG )
{
wxImage * id3cover = guTagGetPicture( CoverPath );
if( id3cover )
{
CoverImage = * id3cover;
delete id3cover;
}
else
guLogError( wxT( "Could not retrieve the image from '%s'" ), CoverPath.c_str() );
}
else if( CoverType == GU_SONGCOVER_FILE )
{
CoverImage.LoadFile( CoverPath );
}
else if( CoverType == GU_SONGCOVER_NONE )
{
CoverImage = guImage( guIMAGE_INDEX_no_cover );
}
else if( CoverType == GU_SONGCOVER_RADIO )
{
CoverImage = guImage( guIMAGE_INDEX_net_radio );
}
else if( CoverType == GU_SONGCOVER_PODCAST )
{
CoverImage = guImage( guIMAGE_INDEX_podcast );
}
//
if( CoverImage.IsOk() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
int CoverFrame = Config->ReadNum( CONFIG_KEY_GENERAL_COVER_FRAME, guCOVERFRAME_DEFAULT, CONFIG_PATH_GENERAL );
if( CoverFrame == guCOVERFRAME_DEFAULT )
{
wxBitmap * BlankCD = new wxBitmap( guImage( guIMAGE_INDEX_blank_cd_cover ) );
if( BlankCD )
{
if( BlankCD->IsOk() )
{
// 38,6
wxMemoryDC MemDC;
MemDC.SelectObject( * BlankCD );
CoverImage.Rescale( 250, 250, wxIMAGE_QUALITY_HIGH );
MemDC.DrawBitmap( wxBitmap( CoverImage ), 34, 4, false );
m_CoverBitmap->SetBitmap( * BlankCD );
//m_CoverBitmap->SetBitmap( wxBitmap( CoverImage ) );
m_CoverBitmap->Refresh();
}
SetSize( BlankCD->GetWidth(), BlankCD->GetHeight() );
delete BlankCD;
}
}
else //if( CoverFrame == guCOVERFRAME_NONE )
{
CoverImage.Rescale( 300, 300, wxIMAGE_QUALITY_HIGH );
m_CoverBitmap->SetBitmap( CoverImage );
m_CoverBitmap->Refresh();
SetSize( 300, 300 );
}
// else // guCOVERFRAME_CUSTOM
// {
// }
Layout();
}
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::CoverFrameActivate( wxActivateEvent &event )
{
if( !event.GetActive() )
Close();
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::OnCaptureLost( wxMouseCaptureLostEvent &event )
{
m_CapturedMouse = false;
Close();
}
// -------------------------------------------------------------------------------- //
void guCoverFrame::OnMouse( wxMouseEvent &event )
{
int MouseX, MouseY;
wxGetMousePosition( &MouseX, &MouseY );
wxRect WinRect = m_CoverBitmap->GetScreenRect();
if( !WinRect.Contains( MouseX, MouseY ) )
{
Close();
}
else
{
if( !m_CapturedMouse )
{
m_CapturedMouse = true;
CaptureMouse();
}
}
if( m_AutoCloseTimer )
m_AutoCloseTimer->Stop();
event.Skip();
}
}
// -------------------------------------------------------------------------------- //
| 7,146
|
C++
|
.cpp
| 187
| 32.406417
| 142
| 0.549351
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,585
|
Amazon.cpp
|
anonbeat_guayadeque/src/ui/cover/Amazon.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Amazon.h"
#include "CoverEdit.h"
#include "Utils.h"
#include "sha2.h"
#include "hmac_sha2.h"
#include <wx/arrimpl.cpp>
#include <wx/base64.h>
#include <wx/statline.h>
#include <wx/sstream.h>
// see http://docs.amazonwebservices.com/AWSEcommerceService/2005-03-23/
// http://webservices.amazon.com/onca/xml?Service=AWSECommerceService
// &SubscriptionId=[YourSubscription IDHere]
// &Operation=ItemSearch
// &Artist=[The artist name]
// &Keywords=[A Keywords String]
// &SearchIndex=Music
// &ItemPage=[The page Num {1..x}]
#define AMAZON_SEARCH_APIKEY "AKIAI3VJGDYXLU7N2HKQ"
#define AMAZON_ASSOCIATE_TAG "guaymusiplay-20"
#define AMAZON_SEARCH_URL wxT( "http://ecs.amazonaws.com/onca/xml?" )
#define AMAZON_SEARCH_PARAMS wxT( "AWSAccessKeyId=" AMAZON_SEARCH_APIKEY \
"&AssociateTag=guaymusiplay-20" \
"&ItemPage=%u" \
"&Keywords=%s" \
"&Operation=ItemSearch" \
"&ResponseGroup=Images" \
"&SearchIndex=All" \
"&Service=AWSECommerceService" \
"&Timestamp=%s" \
"&Version=2009-11-01" )
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guAmazonCoverFetcher::guAmazonCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
wxArrayString guAmazonCoverFetcher::GetImageInfo( wxXmlNode * XmlNode )
{
wxArrayString RetVal;
wxString ImageUrl = wxEmptyString;
wxString Height = wxEmptyString;
wxString Width = wxEmptyString;
wxXmlNode * XmlSubNode;
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "SmallImage" ) && ImageUrl.IsEmpty() )
{
XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "URL" ) )
{
ImageUrl = XmlSubNode->GetNodeContent();
}
else if( XmlSubNode->GetName() == wxT( "Height" ) )
{
Height = XmlSubNode->GetNodeContent();
}
else if( XmlSubNode->GetName() == wxT( "Width" ) )
{
Width = XmlSubNode->GetNodeContent();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
else if( XmlNode->GetName() == wxT( "LargeImage" ) )
{
XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "URL" ) )
{
ImageUrl = XmlSubNode->GetNodeContent();
}
else if( XmlSubNode->GetName() == wxT( "Height" ) )
{
Height = XmlSubNode->GetNodeContent();
}
else if( XmlSubNode->GetName() == wxT( "Width" ) )
{
Width = XmlSubNode->GetNodeContent();
}
XmlSubNode = XmlSubNode->GetNext();
}
}
XmlNode = XmlNode->GetNext();
}
//guLogMessage( wxT( "Found cover %s x %s '%s'" ), Width.c_str(), Height.c_str(), ImageUrl.c_str() );
if( !ImageUrl.IsEmpty() )
{
RetVal.Add( ImageUrl );
RetVal.Add( Width + wxT( " x " ) + Height );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guAmazonCoverFetcher::ExtractImagesInfo( wxString &content )
{
int RetVal = 0;
wxStringInputStream ins( content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlSubNode;
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "ItemSearchResponse" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "Items" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "Request" ) )
{
XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "IsValid" ) )
{
if( XmlSubNode->GetNodeContent() != wxT( "True" ) )
{
guLogError( wxT( "There was an error in the amazon search request." ) );
}
break;
}
XmlSubNode = XmlSubNode->GetNext();
}
}
else if( XmlNode->GetName() == wxT( "Errors" ) )
{
XmlSubNode = XmlNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "Error" ) )
{
XmlSubNode = XmlSubNode->GetChildren();
while( XmlSubNode )
{
if( XmlSubNode->GetName() == wxT( "Message" ) )
{
guLogError( wxT( "Error: %s" ), XmlSubNode->GetNodeContent().c_str() );
break;
}
XmlSubNode = XmlSubNode->GetNext();
}
return 0;
}
XmlSubNode = XmlSubNode->GetNext();
}
}
else if( XmlNode->GetName() == wxT( "Item" ) )
{
wxArrayString CurItem = GetImageInfo( XmlNode );
if( CurItem.Count() )
{
m_CoverLinks->Add( CurItem );
RetVal++;
}
}
XmlNode = XmlNode->GetNext();
}
break;
}
XmlNode = XmlNode->GetNext();
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void inline HMACSha256( char * key, unsigned int key_size,
char * message, unsigned int message_len,
char * mac, unsigned mac_size )
{
return hmac_sha256( ( unsigned char * ) key, key_size,
( unsigned char * ) message, message_len,
( unsigned char * ) mac, mac_size );
}
// -------------------------------------------------------------------------------- //
wxString percentEncodeRfc3986( const wxString &text )
{
wxString RetVal = text;
RetVal.Replace( wxT( "+" ), wxT( "%20" ) );
RetVal.Replace( wxT( "*" ), wxT( "%2A" ) );
RetVal.Replace( wxT( "%7E" ), wxT( "~" ) );
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString GetAmazonSign( const wxString &text )
{
#define AMAZON_SEARCH_SECRETL wxT( "ICsfRx7YNpBBamJyJcol" )
#define AMAZON_SEARCH_SECRETR wxT( "N0qGKH6bBG7NlA9kLqhq" )
wxString Str = wxT( "GET\necs.amazonaws.com\n/onca/xml\n" ) + text;
//guLogMessage( wxT( "String : '%s'" ), Str.c_str() );
wxString Key = AMAZON_SEARCH_SECRETL AMAZON_SEARCH_SECRETR;
char * Output = ( char * ) malloc( 1024 );
HMACSha256( Key.char_str(), Key.Length(), Str.char_str(), Str.Length(), Output, SHA256_DIGEST_SIZE );
wxString Sign = wxBase64Encode( Output, SHA256_DIGEST_SIZE );
//guLogMessage( wxT( "Signature: '%s'" ), Sign.c_str() );
Sign.Replace( wxT( "+" ), wxT( "%2B" ) );
Sign.Replace( wxT( "=" ), wxT( "%3D" ) );
//guLogMessage( wxT( "Encoded: '%s'" ), Sign.c_str() );
free( Output );
return Sign;
}
// -------------------------------------------------------------------------------- //
int guAmazonCoverFetcher::AddCoverLinks( int pagenum )
{
wxDateTime CurTime = wxDateTime::Now();
wxString SearchParams = wxString::Format( AMAZON_SEARCH_PARAMS,
pagenum + 1,
percentEncodeRfc3986( guURLEncode( m_Artist + wxT( " " ) + m_Album ) ).c_str(),
guURLEncode( CurTime.ToUTC().Format( wxT( "%Y-%m-%dT%H:%M:%S.000Z" ) ) ).c_str() );
SearchParams.Replace( wxT( "," ), wxT( "%2C" ) );
wxString SignText = GetAmazonSign( SearchParams );
wxString SearchUrl = AMAZON_SEARCH_URL + SearchParams + wxT( "&Signature=" ) + SignText;
//guLogMessage( wxT( "URL: %u %s" ), pagenum, SearchUrl.c_str() );
if( !m_MainThread->TestDestroy() )
{
//printf( "Buffer:\n%s\n", Buffer );
wxString Content = GetUrlContent( SearchUrl );
//Content = http.GetContent( SearchUrl, 60 );
//guLogMessage( wxT( "Amazon Response:\n%s" ), Content.c_str() );
if( Content.Length() )
{
if( !m_MainThread->TestDestroy() )
{
return ExtractImagesInfo( Content );
}
}
else
{
guLogError( wxT( "Could not get the remote data from connection" ) );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 11,127
|
C++
|
.cpp
| 263
| 30.190114
| 114
| 0.461382
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,586
|
CoverFetcher.cpp
|
anonbeat_guayadeque/src/ui/cover/CoverFetcher.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CoverFetcher.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
// guCoverFetcher
// -------------------------------------------------------------------------------- //
guCoverFetcher::guCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album )
{
m_MainThread = mainthread;
m_CoverLinks = coverlinks;
m_Artist = wxString( artist );
m_Album = wxString( album );
}
// -------------------------------------------------------------------------------- //
guCoverFetcher::~guCoverFetcher()
{
}
// -------------------------------------------------------------------------------- //
bool guCoverFetcher::CoverLinkExist( const wxString &coverlink )
{
int Count = m_CoverLinks->Count();
for( int Index = 0; Index < Count; Index++ )
{
const wxArrayString Cover = m_CoverLinks->Item( Index );
if( Cover[ 0 ] == coverlink )
return true;
}
return false;
}
}
// -------------------------------------------------------------------------------- //
| 2,230
|
C++
|
.cpp
| 52
| 39.788462
| 102
| 0.50023
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,587
|
Yahoo.cpp
|
anonbeat_guayadeque/src/ui/cover/Yahoo.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Yahoo.h"
#include "CoverEdit.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/statline.h>
#include <wx/html/htmlpars.h>
namespace Guayadeque {
#define YAHOO_IMAGES_SEARCH_URL wxT( "http://images.search.yahoo.com/search/images?&p=%s" )
// -------------------------------------------------------------------------------- //
guYahooCoverFetcher::guYahooCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
void guYahooCoverFetcher::ExtractImageInfo( const wxString &content )
{
//guLogMessage( wxT( "ExtractImageInfo: '%s'" ), content.c_str() );
wxArrayString CurImageInfo;
wxString ImgUrl = ExtractString( content, wxT( "&imgurl=" ), wxT( "&" ) );
ImgUrl.Replace( wxT( "%2F" ), wxT( "/" ) );
CurImageInfo.Add( ImgUrl );
wxString ImgInfo = ExtractString( content, wxT( "&w=" ), wxT( "&" ) );
if( !ImgInfo.IsEmpty() )
ImgInfo += wxT( " x " ) + ExtractString( content, wxT( "&h=" ), wxT( "&" ) );
CurImageInfo.Add( ImgInfo );
m_CoverLinks->Add( CurImageInfo );
}
// -------------------------------------------------------------------------------- //
int guYahooCoverFetcher::ExtractImagesInfo( wxString &content, int count )
{
int ImageIndex = 0;
while( !m_MainThread->TestDestroy() )
{
int FindPos = content.Find( wxT( "<li class=\"ld" ) );
if( FindPos == wxNOT_FOUND )
break;
content = content.Mid( FindPos );
FindPos = content.Find( wxT( "</li>" ) );
if( FindPos == wxNOT_FOUND )
break;
ExtractImageInfo( content.Mid( 0, FindPos + 5 ) );
ImageIndex++;
if( ImageIndex > count )
break;
content = content.Mid( FindPos + 4 );
if( content.IsEmpty() )
break;
}
return 0;
}
// -------------------------------------------------------------------------------- //
int guYahooCoverFetcher::AddCoverLinks( int pagenum )
{
wxString SearchString = wxString::Format( wxT( "\"%s\" \"%s\"" ), m_Artist.c_str(), m_Album.c_str() );
//guLogMessage( wxT( "URL: %u %s" ), m_CurrentPage, m_SearchString.c_str() );
wxString SearchUrl = wxString::Format( YAHOO_IMAGES_SEARCH_URL, guURLEncode( SearchString ).c_str() );
//guLogMessage( wxT( "URL: %u %s" ), pagenum, SearchUrl.c_str() );
if( !m_MainThread->TestDestroy() )
{
//printf( "Buffer:\n%s\n", Buffer );
wxString Content = GetUrlContent( SearchUrl );
if( Content.Length() )
{
if( !m_MainThread->TestDestroy() )
{
//guLogMessage( wxT( "Google:====>>>>\n%s\n<<<<====" ), Content.c_str() );
return ExtractImagesInfo( Content, 32 );
}
}
else
{
guLogError( wxT( "Could not get the remote data from connection" ) );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 4,264
|
C++
|
.cpp
| 100
| 37.41
| 112
| 0.533141
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,588
|
Discogs.cpp
|
anonbeat_guayadeque/src/ui/cover/Discogs.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Discogs.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/sstream.h>
#include <wx/xml/xml.h>
#include <wx/tokenzr.h>
#define guDISCOGS_BASEURL "http://www.discogs.com"
#define guDISCOGS_QUERY_APIKEY "b955caf59c"
#define guDISCOGS_QUERY_ARTIST guDISCOGS_BASEURL "/artist/%s?f=xml&api_key=" guDISCOGS_QUERY_APIKEY
#define guDISCOGS_QUERY_RELEASE guDISCOGS_BASEURL "/release/%u?f=xml&api_key=" guDISCOGS_QUERY_APIKEY
#define guDISCOGS_QUERY_SEARCH guDISCOGS_BASEURL "/search?type=all&q=%s&f=xml&api_key=" guDISCOGS_QUERY_APIKEY
#define guDISCOGS_REQUEST_ITEMS 10
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
WX_DEFINE_OBJARRAY( guDiscogsImageArray )
WX_DEFINE_OBJARRAY( guDiscogsTrackArray )
WX_DEFINE_OBJARRAY( guDiscogsReleaseArray )
// -------------------------------------------------------------------------------- //
guDiscogs::guDiscogs()
{
}
// -------------------------------------------------------------------------------- //
guDiscogs::~guDiscogs()
{
}
// -------------------------------------------------------------------------------- //
void GetImages( wxXmlNode * XmlNode, guDiscogsImageArray * images )
{
wxASSERT( XmlNode );
wxASSERT( images );
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "image" ) )
{
guDiscogsImage * Image = new guDiscogsImage();
XmlNode->GetAttribute( wxT( "uri" ), &Image->m_Url );
wxString Value;
XmlNode->GetAttribute( wxT( "width" ), &Value );
long Width = 0;
Value.ToLong( &Width );
Image->m_Width = Width;
XmlNode->GetAttribute( wxT( "height" ), &Value );
long Height = 0;
Value.ToLong( &Height );
Image->m_Height = Height;
images->Add( Image );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
wxArrayString GetUrls( wxXmlNode * XmlNode )
{
wxASSERT( XmlNode );
wxArrayString RetVal;
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "url" ) )
{
RetVal.Add( XmlNode->GetNodeContent() );
}
XmlNode = XmlNode->GetNext();
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void GetRelease( wxXmlNode * XmlNode, guDiscogsRelease * release )
{
wxASSERT( XmlNode );
wxASSERT( release );
//guLogMessage( wxT( "GetRelease..." ) );
while( XmlNode )
{
//guLogMessage( wxT( "GetReleases >> %s" ), XmlNode->GetName().c_str() );
if( XmlNode->GetName() == wxT( "title" ) )
{
release->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "format" ) )
{
release->m_Format = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "year" ) )
{
long LongValue;
XmlNode->GetNodeContent().ToLong( &LongValue );
release->m_Year = LongValue;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void GetReleases( wxXmlNode * XmlNode, guDiscogsReleaseArray * releases )
{
wxASSERT( XmlNode );
wxASSERT( releases );
//guLogMessage( wxT( "GetReleases..." ) );
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "release" ) )
{
//guLogMessage( wxT( "reading release..." ) );
guDiscogsRelease * Release = new guDiscogsRelease();
wxString Value;
long LongValue;
XmlNode->GetAttribute( wxT( "id" ), &Value );
Value.ToLong( &LongValue );
Release->m_Id = LongValue;
XmlNode->GetAttribute( wxT( "type" ), &Release->m_Type );
GetRelease( XmlNode->GetChildren(), Release );
releases->Add( Release );
}
else
{
guLogError( wxT( "GetReleases: the node is not a release" ) );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void GetTrack( wxXmlNode * XmlNode, guDiscogsTrack * track )
{
wxASSERT( XmlNode );
wxASSERT( track );
while( XmlNode )
{
wxString Value;
if( XmlNode->GetName() == wxT( "position" ) )
{
long LongValue;
XmlNode->GetNodeContent().ToLong( &LongValue );
track->m_Position = LongValue;
}
else if( XmlNode->GetName() == wxT( "title" ) )
{
track->m_Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "duration" ) )
{
Value = XmlNode->GetNodeContent();
long minutes;
long seconds;
Value.BeforeFirst( wxT( ':' ) ).ToLong( &minutes );
Value.AfterFirst( wxT( ':' ) ).ToLong( &seconds );
track->m_Length = ( minutes * 60 ) + seconds;
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void GetTracks( wxXmlNode * XmlNode, guDiscogsTrackArray * tracks )
{
wxASSERT( XmlNode );
wxASSERT( tracks );
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "track" ) )
{
guDiscogsTrack * Track = new guDiscogsTrack();
GetTrack( XmlNode->GetChildren(), Track );
tracks->Add( Track );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
bool guDiscogs::GetArtist( const wxString &name, guDiscogsArtist * artist )
{
wxASSERT( !name.IsEmpty() );
wxASSERT( artist );
wxString SearchUrl;
SearchUrl = wxString::Format( wxT( guDISCOGS_QUERY_ARTIST ), guURLEncode( name ).c_str() );
wxString Content = GetUrlContent( SearchUrl, wxEmptyString, true );
//guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
if( !Content.IsEmpty() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && ( XmlNode->GetName() == wxT( "resp" ) ) )
{
wxString Status;
XmlNode->GetAttribute( wxT( "stat" ), &Status );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "artist" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
//guLogMessage( wxT( "GetArtist >> %s" ), XmlNode->GetName().c_str() );
if( XmlNode->GetName() == wxT( "images" ) )
{
GetImages( XmlNode->GetChildren(), &artist->m_Images );
}
else if( XmlNode->GetName() == wxT( "name" ) )
{
artist->m_Name = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "realname" ) )
{
artist->m_RealName = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName() == wxT( "urls" ) )
{
artist->m_Urls = GetUrls( XmlNode->GetChildren() );
}
else if( XmlNode->GetName() == wxT( "releases" ) )
{
GetReleases( XmlNode->GetChildren(), &artist->m_Releases );
}
XmlNode = XmlNode->GetNext();
}
return true;
}
else
{
guLogError( wxT( "Could not get the artist xml data" ) );
}
}
else
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "error" ) )
{
wxString ErrorMsg;
XmlNode->GetAttribute( wxT( "msg" ), &ErrorMsg );
guLogError( wxT( "guDiscogs: %s" ), ErrorMsg.c_str() );
}
else
{
guLogError( wxT( "guDiscogs error getting artist" ) );
}
}
}
else
{
guLogError( wxT( "Got no valid response from the Discogs server" ) );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guDiscogs::GetReleaseImages( const int id, guDiscogsRelease * release )
{
return false;
}
// -------------------------------------------------------------------------------- //
bool guDiscogs::GetRelease( const int id, guDiscogsRelease * release )
{
wxString SearchUrl;
SearchUrl = wxString::Format( wxT( guDISCOGS_QUERY_RELEASE ), id );
wxString Content = GetUrlContent( SearchUrl, wxEmptyString, true );
//guLogMessage( wxT( "GetRelease:\n%s" ), Content.c_str() );
if( !Content.IsEmpty() )
{
wxStringInputStream ins( Content );
wxXmlDocument XmlDoc( ins );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && ( XmlNode->GetName() == wxT( "resp" ) ) )
{
wxString Status;
XmlNode->GetAttribute( wxT( "stat" ), &Status );
if( Status == wxT( "ok" ) )
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "release" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "images" ) )
{
GetImages( XmlNode->GetChildren(), &release->m_Images );
}
else if( XmlNode->GetName() == wxT( "tracklist" ) )
{
GetTracks( XmlNode->GetChildren(), &release->m_Tracks );
}
XmlNode = XmlNode->GetNext();
}
return true;
}
}
else
{
XmlNode = XmlNode->GetChildren();
if( XmlNode->GetName() == wxT( "error" ) )
{
wxString ErrorMsg;
XmlNode->GetAttribute( wxT( "msg" ), &ErrorMsg );
guLogError( wxT( "guDiscogs: %s" ), ErrorMsg.c_str() );
}
else
{
guLogError( wxT( "guDiscogs error getting artist" ) );
}
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
guDiscogsCoverFetcher::guDiscogsCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
guDiscogsCoverFetcher::~guDiscogsCoverFetcher()
{
}
// -------------------------------------------------------------------------------- //
bool GetNameMatch( const wxString &title, const wxString &search )
{
wxArrayString SearchWords = wxStringTokenize( search );
int count = SearchWords.Count();
for( int index = 0; index < count; index++ )
{
if( title.Find( SearchWords[ index ].Lower() ) == wxNOT_FOUND )
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
int guDiscogsCoverFetcher::AddCoverLinks( int pagenum )
{
guDiscogs Discogs;
guDiscogsArtist Artist;
Discogs.GetArtist( m_Artist, &Artist );
int Count = wxMin( (int) Artist.m_Releases.Count(), ( pagenum + 1 ) * guDISCOGS_REQUEST_ITEMS );
int CheckCount = 0;
//guLogMessage( wxT( "Reading %s %i Releases..." ), m_Artist.c_str(), Count );
for( int Index = ( pagenum * guDISCOGS_REQUEST_ITEMS ); Index < Count; Index++ )
{
// guLogMessage( wxT( "Release '%s' type '%s' format '%s'" ),
// Artist.m_Releases[ Index ].m_Title.c_str(),
// Artist.m_Releases[ Index ].m_Type.c_str(),
// Artist.m_Releases[ Index ].m_Format.c_str() );
if( Artist.m_Releases[ Index ].m_Type == wxT( "Main" ) &&
GetNameMatch( Artist.m_Releases[ Index ].m_Title.Lower(), m_Album ) )
{
Discogs.GetRelease( Artist.m_Releases[ Index ].m_Id, &Artist.m_Releases[ Index ] );
int ImgIndex;
int ImgCount = Artist.m_Releases[ Index ].m_Images.Count();
for( ImgIndex = 0; ImgIndex < ImgCount; ImgIndex++ )
{
wxArrayString ImgArray;
ImgArray.Add( Artist.m_Releases[ Index ].m_Images[ ImgIndex ].m_Url );
ImgArray.Add( wxString::Format( wxT( "%ix%i" ),
Artist.m_Releases[ Index ].m_Images[ ImgIndex ].m_Width,
Artist.m_Releases[ Index ].m_Images[ ImgIndex ].m_Height ) );
m_CoverLinks->Add( ImgArray );
// guLogMessage( wxT( "Added Image %s" ),
// Artist.m_Releases[ Index ].m_Images[ ImgIndex ].m_Url.c_str() );
break;
}
}
CheckCount++;
}
return CheckCount;
}
}
// -------------------------------------------------------------------------------- //
| 15,125
|
C++
|
.cpp
| 386
| 29.580311
| 116
| 0.468559
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,589
|
LastFMCovers.cpp
|
anonbeat_guayadeque/src/ui/cover/LastFMCovers.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "LastFMCovers.h"
#include "LastFM.h"
#include "Utils.h"
#include <wx/string.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guLastFMCoverFetcher::guLastFMCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
int guLastFMCoverFetcher::AddCoverLinks( int pagenum )
{
guLastFM * LastFM;
wxString AlbumName;
guAlbumInfo AlbumInfo;
if( pagenum > 0 )
return 0;
LastFM = new guLastFM();
if( LastFM )
{
// Remove from album name expressions like (cd1),(cd2) etc
AlbumName = RemoveSearchFilters( m_Album );
AlbumInfo = LastFM->AlbumGetInfo( m_Artist, AlbumName );
if( LastFM->IsOk() )
{
if( !AlbumInfo.m_ImageLink.IsEmpty() )
{
wxArrayString ImageInfo;
ImageInfo.Add( AlbumInfo.m_ImageLink );
ImageInfo.Add( wxEmptyString );
m_CoverLinks->Add( ImageInfo );
}
}
else
{
// There was en error...
guLogError( wxT( "Error getting the cover for %s - %s (%u)" ),
m_Artist.c_str(),
AlbumName.c_str(),
LastFM->GetLastError() );
}
delete LastFM;
}
return 1;
}
}
// -------------------------------------------------------------------------------- //
| 2,738
|
C++
|
.cpp
| 70
| 32.928571
| 114
| 0.525226
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,590
|
CoverPanel.cpp
|
anonbeat_guayadeque/src/ui/cover/CoverPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CoverPanel.h"
#include "Images.h"
#include "TagInfo.h"
#define guCOVERPANEL_RESIZE_TIMER_TIME 250
#define guCOVERPANEL_RESIZE_TIMER_ID 10
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guCoverPanel::guCoverPanel( wxWindow * parent, guPlayerPanel * playerpanel ) :
wxPanel( parent, wxID_ANY, wxDefaultPosition, wxSize( 100, 100 ), wxTAB_TRAVERSAL ),
m_ResizeTimer( this, guCOVERPANEL_RESIZE_TIMER_ID )
{
m_PlayerPanel = playerpanel;
m_LastSize = 100;
Bind( wxEVT_SIZE, &guCoverPanel::OnSize, this );
Bind( wxEVT_PAINT, &guCoverPanel::OnPaint, this );
Bind( wxEVT_TIMER, &guCoverPanel::OnResizeTimer, this, guCOVERPANEL_RESIZE_TIMER_ID );
wxCommandEvent Event;
OnUpdatedTrack( Event );
}
// -------------------------------------------------------------------------------- //
guCoverPanel::~guCoverPanel()
{
Unbind( wxEVT_SIZE, &guCoverPanel::OnSize, this );
Unbind( wxEVT_PAINT, &guCoverPanel::OnPaint, this );
Unbind( wxEVT_TIMER, &guCoverPanel::OnResizeTimer, this, guCOVERPANEL_RESIZE_TIMER_ID );
}
// -------------------------------------------------------------------------------- //
void guCoverPanel::OnPaint( wxPaintEvent &event )
{
wxCoord Width;
wxCoord Height;
GetClientSize( &Width, &Height );
if( Width && Height )
{
wxMutexLocker Lock( m_CoverImageMutex );
wxPaintDC dc( this );
dc.DrawBitmap( m_CoverImage, ( Width - m_LastSize ) / 2, ( Height - m_LastSize ) / 2, false );
}
}
// -------------------------------------------------------------------------------- //
void guCoverPanel::OnResizeTimer( wxTimerEvent &event )
{
UpdateImage();
}
// -------------------------------------------------------------------------------- //
void guCoverPanel::OnSize( wxSizeEvent &event )
{
wxSize Size = event.GetSize();
int MinSize = wxMin( Size.GetWidth(), Size.GetHeight() );
//guLogMessage( wxT( "NewSize: %u" ), MinSize );
if( MinSize != m_LastSize )
{
m_LastSize = MinSize;
//guLogMessage( wxT( "Updating Size: %u" ), MinSize );
// UpdateImage();
if( m_ResizeTimer.IsRunning() )
{
m_ResizeTimer.Stop();
}
m_ResizeTimer.Start( guCOVERPANEL_RESIZE_TIMER_TIME, wxTIMER_ONE_SHOT );
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guCoverPanel::UpdateImage( void )
{
wxImage * CoverImage = NULL;
switch( m_CoverType )
{
case GU_SONGCOVER_FILE :
CoverImage = new wxImage( m_CoverPath );
break;
case GU_SONGCOVER_ID3TAG :
CoverImage = guTagGetPicture( m_CoverPath );
break;
case GU_SONGCOVER_RADIO :
CoverImage = new wxImage( guImage( guIMAGE_INDEX_net_radio ) );
break;
case GU_SONGCOVER_PODCAST :
CoverImage = new wxImage( guImage( guIMAGE_INDEX_podcast ) );
break;
default :
break;
}
if( !CoverImage || !CoverImage->IsOk() )
{
if( CoverImage )
delete CoverImage;
CoverImage = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
}
if( CoverImage )
{
if( m_LastSize > 0 )
CoverImage->Rescale( m_LastSize, m_LastSize, wxIMAGE_QUALITY_HIGH );
wxMutexLocker Lock( m_CoverImageMutex );
m_CoverImage = wxBitmap( * CoverImage );
//Update();
Refresh();
delete CoverImage;
}
}
// -------------------------------------------------------------------------------- //
void guCoverPanel::OnUpdatedTrack( wxCommandEvent &event )
{
const guCurrentTrack * CurrentTrack = m_PlayerPanel->GetCurrentTrack();
if( CurrentTrack )
{
m_CoverType = CurrentTrack->m_CoverType;
m_CoverPath = CurrentTrack->m_CoverPath;
guLogMessage( wxT( "Changed image to %i '%s'" ), m_CoverType, m_CoverPath.c_str() );
}
else
{
m_CoverType = GU_SONGCOVER_NONE;
m_CoverPath = wxEmptyString;
}
UpdateImage();
}
}
// -------------------------------------------------------------------------------- //
| 5,294
|
C++
|
.cpp
| 141
| 32.64539
| 102
| 0.54425
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,591
|
Apple.cpp
|
anonbeat_guayadeque/src/ui/cover/Apple.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Apple.h"
#include "CoverEdit.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/base64.h>
#include <wx/statline.h>
#include <wx/sstream.h>
#include "json/json.h"
#define APPLE_SEARCH_URL wxT( "https://itunes.apple.com/search?term=" )
#define APPLE_SEARCH_PARAMS wxT( "&limit=30" )
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guAppleCoverFetcher::guAppleCoverFetcher( guFetchCoverLinksThread * mainthread, guArrayStringArray * coverlinks,
const wxChar * artist, const wxChar * album ) :
guCoverFetcher( mainthread, coverlinks, artist, album )
{
}
// -------------------------------------------------------------------------------- //
int guAppleCoverFetcher::ExtractImagesInfo( wxString &content )
{
int RetVal = 0;
Json::Reader reader;
Json::Value RespObject;
reader.parse( std::string( content.mb_str() ), RespObject );
if( RespObject.isMember( "results" ) )
{
//guLogMessage( wxT( "Got the results..." ) );
Json::Value Results = RespObject[ "results" ];
if( Results.isArray() )
{
int Count = Results.size();
//guLogMessage( wxT( "Results is array....%d" ), Count );
for( int Index = 0; Index < Count; Index++ )
{
Json::Value Result = Results[ Index ];
//guLogMessage( "Object in result %s", Result.asString() );
if( Result.isMember( "artworkUrl100" ) )
{
wxString CoverLink = wxString( Result[ "artworkUrl100" ].asString() );
if( !CoverLink.IsEmpty() )
{
CoverLink.Replace( wxT( "100x100" ), wxT( "500x500" ) );
if( !CoverLinkExist( CoverLink ) )
{
wxArrayString CoverItem;
CoverItem.Add( CoverLink );
CoverItem.Add( wxT( "500x500" ) );
m_CoverLinks->Add( CoverItem );
RetVal++;
}
}
}
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guAppleCoverFetcher::AddCoverLinks( int pagenum )
{
wxString SearchParams = guURLEncode( m_Artist + wxT( " " ) + m_Album ) +
APPLE_SEARCH_PARAMS;
SearchParams.Replace( wxT( "," ), wxT( "%2C" ) );
wxString SearchUrl = APPLE_SEARCH_URL + SearchParams;
//guLogMessage( wxT( "URL: %u %s" ), pagenum, SearchUrl.c_str() );
if( !m_MainThread->TestDestroy() )
{
//printf( "Buffer:\n%s\n", Buffer );
wxString Content = GetUrlContent( SearchUrl );
//Content = http.GetContent( SearchUrl, 60 );
//guLogMessage( wxT( "Amazon Response:\n%s" ), Content.c_str() );
if( Content.Length() )
{
if( !m_MainThread->TestDestroy() )
{
return ExtractImagesInfo( Content );
}
}
else
{
guLogError( wxT( "Could not get the remote data from connection" ) );
}
}
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 4,475
|
C++
|
.cpp
| 108
| 33.037037
| 112
| 0.503447
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,592
|
PlayerPanel.cpp
|
anonbeat_guayadeque/src/ui/player/PlayerPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayerPanel.h"
#include "EventCommandIds.h"
#include "CoverFrame.h"
#include "CoverPanel.h"
#include "Config.h"
#include "DbLibrary.h"
#include "Equalizer.h"
#include "FileRenamer.h" // NormalizeField
#include "Images.h"
#include "LevelInfo.h"
#include "MainFrame.h"
#include "RadioTagInfo.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Utils.h"
#include <wx/gdicmn.h>
#include <wx/regex.h>
#include <wx/utils.h>
namespace Guayadeque {
#define GUPLAYER_MIN_PREVTRACK_POS 5000
#define guPLAYER_SMART_CACHEITEMS 100
#define guPLAYER_SMART_CACHEARTISTS 20
#define guPLAYER_ICONS_SEPARATOR 2
#define guPLAYER_ICONS_GROUPSEPARATOR 4
wxArrayInt SupportedPlayCountTypes;
// -------------------------------------------------------------------------------- //
guPlayerPanel::guPlayerPanel( wxWindow * parent, guDbLibrary * db,
guPlayList * playlist, guPlayerFilters * filters )
: wxPanel( parent, wxID_ANY, wxDefaultPosition, wxSize( 310, 170 ), wxTAB_TRAVERSAL )
{
double SavedVol;
m_Db = db;
m_MainFrame = ( guMainFrame * ) parent;
m_PlayListCtrl = playlist;
m_NotifySrv = NULL;
m_PlayerFilters = filters;
m_BufferGaugeId = wxNOT_FOUND;
//m_PendingNewRecordName = false;
m_MediaSong.m_Type = guTRACK_TYPE_NOTDB;
m_MediaSong.m_SongId = 0;
m_MediaSong.m_Length = 0;
m_MediaSong.m_CoverType = GU_SONGCOVER_NONE;
wxFont CurrentFont = wxSystemSettings::GetFont( wxSYS_SYSTEM_FONT );
// For the Load configuration
wxArrayString Songs;
guConfig * Config;
m_LastVolume = wxNOT_FOUND;
m_PlayerVumeters = NULL;
ResetVumeterLevel();
m_LastCurPos = 0;
m_LastLength = 0;
m_LastPlayState = -1; //guMEDIASTATE_STOPPE;
m_LastTotalLen = -1;
m_TrackStartPos = 0;
m_NextTrackId = 0;
m_CurTrackId = 0;
wxArrayInt Equalizer;
m_SilenceDetector = false;
m_SilenceDetectorLevel = wxNOT_FOUND;
m_SilenceDetectorTime = 0;
m_ShowRevTime = false;
m_PlayRandom = false;
m_PlayRandomMode = guRANDOM_MODE_TRACK;
m_DelTracksPlayed = false;
m_PendingScrob = false;
m_ShowNotifications = true;
m_ShowNotificationsTime = 0;
m_ErrorFound = false;
m_SavedPlayedTrack = false;
m_EnableEq = true;
m_EnableVolCtls = true;
m_SilenceDetected = false;
m_AboutToEndDetected = false;
// Load configuration
Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
//guLogDebug( wxT( "Reading PlayerPanel Config" ) );
SavedVol = Config->ReadNum( CONFIG_KEY_GENERAL_PLAYER_VOLUME, 50, CONFIG_PATH_GENERAL );
//guLogDebug( wxT( "Current Volume Var : %d" ), ( int ) m_CurVolume );
//m_PlayLoop = Config->ReadNum( CONFIG_KEY_GENERAL_PLAYER_LOOP, 0, CONFIG_PATH_GENERAL );
//m_PlaySmart = Config->ReadBool( CONFIG_KEY_GENERAL_PLAYER_SMART, m_PlayLoop ? false : true, CONFIG_PATH_GENERAL );
m_PlayMode = Config->ReadNum( CONFIG_KEY_GENERAL_PLAYER_PLAYMODE, guPLAYER_PLAYMODE_SMART, CONFIG_PATH_GENERAL );
m_PlayRandom = Config->ReadBool( CONFIG_KEY_GENERAL_RANDOM_PLAY_ON_EMPTY_PLAYLIST, false, CONFIG_PATH_GENERAL );
m_PlayRandomMode = Config->ReadNum( CONFIG_KEY_GENERAL_RANDOM_MODE_ON_EMPTY_PLAYLIST, guRANDOM_MODE_TRACK, CONFIG_PATH_GENERAL );
m_ShowNotifications = Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_NOTIFICATIONS, true, CONFIG_PATH_GENERAL );
m_ShowNotificationsTime = Config->ReadNum( CONFIG_KEY_GENERAL_NOTIFICATION_TIME, 0, CONFIG_PATH_GENERAL );
m_EnableEq = Config->ReadBool( CONFIG_KEY_GENERAL_EQ_ENABLED, true, CONFIG_PATH_GENERAL );
m_EnableVolCtls = Config->ReadBool( CONFIG_KEY_GENERAL_VOLUME_ENABLED, true, CONFIG_PATH_GENERAL );
m_SmartPlayAddTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_NUM_TRACKS_TO_ADD, 3, CONFIG_PATH_PLAYBACK );
m_SmartPlayMinTracksToPlay = Config->ReadNum( CONFIG_KEY_PLAYBACK_MIN_TRACKS_PLAY, 4, CONFIG_PATH_PLAYBACK );
m_DelTracksPlayed = Config->ReadBool( CONFIG_KEY_PLAYBACK_DEL_TRACKS_PLAYED, false, CONFIG_PATH_PLAYBACK );
m_SmartMaxArtistsList = Config->ReadNum( CONFIG_KEY_PLAYBACK_SMART_FILTER_ARTISTS, 20, CONFIG_PATH_PLAYBACK );
m_SmartMaxTracksList = Config->ReadNum( CONFIG_KEY_PLAYBACK_SMART_FILTER_TRACKS, 100, CONFIG_PATH_PLAYBACK );
m_AudioScrobbleEnabled = Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM ) ||
Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM );
Equalizer = Config->ReadANum( CONFIG_KEY_EQUALIZER_BAND, 0, CONFIG_PATH_EQUALIZER );
if( Equalizer.Count() != guEQUALIZER_BAND_COUNT )
{
Equalizer.Empty();
Equalizer.Add( 0, guEQUALIZER_BAND_COUNT );
}
m_SilenceDetector = Config->ReadBool( CONFIG_KEY_PLAYBCK_SILENCE_DETECTOR, false, CONFIG_PATH_PLAYBACK );
m_SilenceDetectorLevel = Config->ReadNum( CONFIG_KEY_PLAYBCK_SILENCE_LEVEL, -55, CONFIG_PATH_PLAYBACK );
if( Config->ReadBool( CONFIG_KEY_PLAYBCK_SILENCE_AT_END, false, CONFIG_PATH_PLAYBACK ) )
{
m_SilenceDetectorTime = Config->ReadNum( CONFIG_KEY_PLAYBCK_SILENCE_END_TIME, 45, CONFIG_PATH_PLAYBACK ) * 1000;
}
m_ShowRevTime = Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_REV_TIME, false, CONFIG_PATH_GENERAL );
m_ForceGapless = m_EnableVolCtls ? Config->ReadBool( CONFIG_KEY_CROSSFADER_FORCE_GAPLESS, false, CONFIG_PATH_CROSSFADER ) : true;
m_FadeOutTime = Config->ReadNum( CONFIG_KEY_CROSSFADER_FADEOUT_TIME, 50, CONFIG_PATH_CROSSFADER ) * 100;
m_SliderIsDragged = false;
m_SmartSearchEnabled = false;
m_SmartAddTracksThread = NULL;
// m_UpdateCoverThread = NULL;
// ---------------------------------------------------------------------------- //
// The player controls
// ---------------------------------------------------------------------------- //
// wxPanel * PlayerPanel;
// PlayerPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * PlayerMainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer * PlayerBtnSizer = new wxBoxSizer( wxHORIZONTAL );
//m_PrevTrackButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_prev ), wxDefaultPosition, wxDefaultSize, 0 ); //wxBU_AUTODRAW );
m_PrevTrackButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_prev ), guImage( guIMAGE_INDEX_player_highlight_prev ) );
m_PrevTrackButton->SetToolTip( _( "Go to the playlist previous track" ) );
PlayerBtnSizer->Add( m_PrevTrackButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
//m_PlayButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_play ), wxDefaultPosition, wxDefaultSize, 0 );
m_PlayButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_play ), guImage( guIMAGE_INDEX_player_highlight_play ) );
m_PlayButton->SetToolTip( _( "Play or pause the current track" ) );
PlayerBtnSizer->Add( m_PlayButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
//m_NextTrackButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_next ), wxDefaultPosition, wxDefaultSize, 0 );
m_NextTrackButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_next ), guImage( guIMAGE_INDEX_player_highlight_next ) );
m_NextTrackButton->SetToolTip( _( "Go to the playlist next track" ) );
PlayerBtnSizer->Add( m_NextTrackButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
m_StopButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_stop ), guImage( guIMAGE_INDEX_player_highlight_stop ) );
m_StopButton->SetToolTip( _( "Stops the current track" ) );
PlayerBtnSizer->Add( m_StopButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
m_RecordButton = new guToggleRoundButton( this, guImage( guIMAGE_INDEX_player_light_record ), guImage( guIMAGE_INDEX_player_normal_record ), guImage( guIMAGE_INDEX_player_highlight_record ) );
m_RecordButton->SetToolTip( _( "Record to file" ) );
m_RecordButton->Enable( false );
m_RecordButton->Show( Config->ReadBool( CONFIG_KEY_RECORD_ENABLED, false, CONFIG_PATH_RECORD ) );
PlayerBtnSizer->Add( m_RecordButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT|wxRIGHT, guPLAYER_ICONS_SEPARATOR );
PlayerBtnSizer->Add( guPLAYER_ICONS_GROUPSEPARATOR, 0, 0, wxEXPAND, 5 );
m_PlayModeButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_smart ), guImage( guIMAGE_INDEX_player_highlight_smart ) );
UpdatePlayModeButton();
PlayerBtnSizer->Add( m_PlayModeButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
//m_RandomPlayButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_random ), wxDefaultPosition, wxDefaultSize, 0 );
m_RandomPlayButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_random ), guImage( guIMAGE_INDEX_player_highlight_random ) );
m_RandomPlayButton->SetToolTip( _( "Randomize the tracks in playlist" ) );
PlayerBtnSizer->Add( m_RandomPlayButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
m_ForceGaplessButton = new guRoundButton( this,
guImage( m_ForceGapless ? guIMAGE_INDEX_player_normal_gapless : guIMAGE_INDEX_player_normal_crossfading ),
guImage( m_ForceGapless ? guIMAGE_INDEX_player_highlight_gapless : guIMAGE_INDEX_player_highlight_crossfading ) );
m_ForceGaplessButton->SetToolTip( m_ForceGapless ? _( "Enable crossfading" ) : _( "Disable crossfading" ) );
PlayerBtnSizer->Add( m_ForceGaplessButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT|wxRIGHT, guPLAYER_ICONS_SEPARATOR );
if( !m_EnableVolCtls )
m_ForceGaplessButton->Hide();
PlayerBtnSizer->Add( guPLAYER_ICONS_GROUPSEPARATOR, 0, 0, wxEXPAND, 5 );
//m_EqualizerButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_equalizer ), wxDefaultPosition, wxDefaultSize, 0 );
m_EqualizerButton = new guRoundButton( this, guImage( m_EnableEq ? guIMAGE_INDEX_player_normal_equalizer : guIMAGE_INDEX_player_light_equalizer ), guImage( guIMAGE_INDEX_player_highlight_equalizer ) );
m_EqualizerButton->SetToolTip( _( "Show the equalizer (right click for on/off)" ) );
PlayerBtnSizer->Add( m_EqualizerButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
m_VolumeButton = new guRoundButton( this, guImage( guIMAGE_INDEX_player_normal_vol_mid ), guImage( guIMAGE_INDEX_player_highlight_vol_mid ) );
m_VolumeButton->SetToolTip( _( "Volume" ) + wxString::Format( wxT( " %i%%" ), ( int ) SavedVol ) );
PlayerBtnSizer->Add( m_VolumeButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
if( !m_EnableVolCtls )
m_VolumeButton->Hide();
m_VolumeBar = new wxSlider( this, wxID_ANY, SavedVol, 0, 100 );
m_VolumeBar->SetMinSize( wxSize( 100, 40 ) );
PlayerBtnSizer->Add( m_VolumeBar, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, guPLAYER_ICONS_SEPARATOR );
if( m_EnableVolCtls && Config->ReadBool( CONFIG_KEY_GENERAL_PLAYER_VOLUME_VISIBLE, true, CONFIG_PATH_GENERAL ) )
m_VolumeBar->Show();
else
m_VolumeBar->Hide();
PlayerMainSizer->Add( PlayerBtnSizer, 0, wxEXPAND, 2 );
//m_VolumeButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_player_normal_vol_mid ), wxDefaultPosition, wxDefaultSize, 0 );
wxBoxSizer * PlayerDetailsSizer;
PlayerDetailsSizer = new wxBoxSizer( wxHORIZONTAL );
m_PlayerCoverBitmap = new wxStaticBitmap( this, wxID_ANY, guImage( guIMAGE_INDEX_no_cover ), wxDefaultPosition, wxSize( 100, 100 ), 0 );
//m_PlayerCoverBitmap->SetToolTip( _( "Shows the current track album cover if available" ) );
PlayerDetailsSizer->Add( m_PlayerCoverBitmap, 0, wxALL, 2 );
wxBoxSizer* PlayerLabelsSizer;
PlayerLabelsSizer = new wxBoxSizer( wxVERTICAL );
//m_TitleLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_TitleLabel = new guAutoScrollText( this, wxEmptyString );
m_TitleLabel->SetToolTip( _( "Show the name of the current track" ) );
//m_TitleLabel->Wrap( -1 );
CurrentFont.SetWeight( wxFONTWEIGHT_BOLD );
m_TitleLabel->SetFont( CurrentFont );
PlayerLabelsSizer->Add( m_TitleLabel, 1, wxEXPAND|wxLEFT, 2 );
//m_AlbumLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_AlbumLabel = new guAutoScrollText( this, wxEmptyString );
m_AlbumLabel->SetToolTip( _( "Show the album name of the current track" ) );
//m_AlbumLabel->Wrap( -1 );
CurrentFont.SetPointSize( CurrentFont.GetPointSize() - 1 );
CurrentFont.SetWeight( wxFONTWEIGHT_NORMAL );
CurrentFont.SetStyle( wxFONTSTYLE_ITALIC );
m_AlbumLabel->SetFont( CurrentFont );
PlayerLabelsSizer->Add( m_AlbumLabel, 1, wxEXPAND|wxLEFT, 2 );
//m_ArtistLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_ArtistLabel = new guAutoScrollText( this, wxEmptyString );
m_ArtistLabel->SetToolTip( _( "Show the artist name of the current track" ) );
//m_ArtistLabel->Wrap( -1 );
CurrentFont.SetStyle( wxFONTSTYLE_NORMAL );
m_ArtistLabel->SetFont( CurrentFont );
PlayerLabelsSizer->Add( m_ArtistLabel, 1, wxEXPAND|wxLEFT, 2 );
m_PosLabelSizer = new wxBoxSizer( wxHORIZONTAL );
//m_PosLabelSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_YearLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_YearLabel->SetToolTip( _( "Show the year of the current track" ) );
m_PosLabelSizer->Add( m_YearLabel, 1, wxALIGN_CENTER_VERTICAL|wxLEFT, 2 );
m_PositionLabel = new wxStaticText( this, wxID_ANY, _("00:00 of 00:00"), wxDefaultPosition, wxDefaultSize, 0 );
m_PositionLabel->SetToolTip( _( "Show the current position and song length of the current track" ) );
m_PositionLabel->Wrap( -1 );
m_PosLabelSizer->Add( m_PositionLabel, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 2 );
PlayerLabelsSizer->Add( m_PosLabelSizer, 1, wxEXPAND, 2 );
m_BitRateSizer = new wxBoxSizer( wxHORIZONTAL );
m_Rating = new guRating( this, GURATING_STYLE_MID );
m_BitRateSizer->Add( m_Rating, 0, wxRIGHT|wxALIGN_CENTER_VERTICAL, 2 );
// m_LoveBanButton = new guToggleRoundButton( this, guImage( guIMAGE_INDEX_player_light_love ), guImage( guIMAGE_INDEX_player_normal_love ), guImage( guIMAGE_INDEX_player_highlight_love ) );
// m_LoveBanButton->SetToolTip( _( "Love or Ban a track in AudioScrobble service" ) );
// m_BitRateSizer->Add( m_LoveBanButton, 0, wxEXPAND|wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 2 );
m_BitRateSizer->Add( 0, 0, 1, wxALL, 2 );
m_CodecLabel = new wxStaticText( this, wxID_ANY, "[]", wxDefaultPosition, wxDefaultSize, 0 );
m_CodecLabel->SetToolTip( _( "Show the file format of the current track" ) );
CurrentFont.SetPointSize( CurrentFont.GetPointSize() - 1 );
m_CodecLabel->SetFont( CurrentFont );
m_BitRateSizer->Add( m_CodecLabel, 0, wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 2 );
m_BitRateLabel = new wxStaticText( this, wxID_ANY, "[kbps]", wxDefaultPosition, wxDefaultSize, 0 );
m_BitRateLabel->SetToolTip( _( "Show the bit rate of the current track" ) );
m_BitRateLabel->SetFont( CurrentFont );
m_BitRateSizer->Add( m_BitRateLabel, 0, wxRIGHT|wxLEFT|wxALIGN_CENTER_VERTICAL, 2 );
PlayerLabelsSizer->Add( m_BitRateSizer, 0, wxEXPAND, 2 );
PlayerDetailsSizer->Add( PlayerLabelsSizer, 1, wxEXPAND, 5 );
PlayerMainSizer->Add( PlayerDetailsSizer, 0, wxEXPAND, 5 );
m_PlayerPositionSlider = new wxSlider( this, wxID_ANY, 0, 0, 1000 );
m_PlayerPositionSlider->SetMinSize( wxSize( 100, 40 ) );
PlayerMainSizer->Add( m_PlayerPositionSlider, 0, wxALL|wxEXPAND, 0 );
// SetSizer( PlayerMainSizer );
// Layout();
// PlayerMainSizer->Fit( this );
// SetSizeHints( this );
//PlayerPanel->Layout();
////////////////////////////////////////////////////////////////////////////////////////////////////////
// m_PlayListCtrl = new guPlayList( this, m_Db );
// PlayListSizer->Add( m_PlayListCtrl, 1, wxALL|wxEXPAND, 2 );
// wxPanel * PlayListPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
// wxBoxSizer * PlayListPanelSizer = new wxBoxSizer( wxVERTICAL );
// m_PlayListCtrl = new guPlayList( this, m_Db, this );
//PlayListPanelSizer->Add( m_PlayListCtrl, 1, wxALL|wxEXPAND, 2 );
// PlayerMainSizer->Add( m_PlayListCtrl, 1, wxALL|wxEXPAND, 2 );
// PlayListPanel->SetSizer( PlayListPanelSizer );
// PlayListPanel->Layout();
// PlayListPanelSizer->Fit( PlayListPanel );
// m_AuiManager.AddPane( PlayListPanel, wxAuiPaneInfo().Name( wxT( "PlayerPlayList" ) ).Caption( _( "Playlist" ) ).
// Layer( 0 ).Row( 1 ).Position( 0 ).
// Bottom() );
SetSizer( PlayerMainSizer );
Layout();
PlayerMainSizer->Fit( this );
//PlayerMainSizer->SetSizeHints( this );
//PlayerPanel->Layout();
m_MediaCtrl = new guMediaCtrl( this );
m_MediaRecordCtrl = new guMediaRecordCtrl( this, m_MediaCtrl );
//m_MediaCtrl->Create( this, wxID_ANY );
//
m_PlayListCtrl->ReloadItems();
TrackListChanged();
// The SetVolume call dont get set if the volume is the last one
// so we do it two calls
m_CurVolume = wxNOT_FOUND;
SetVolume( SavedVol );
//guLogDebug( wxT( "CurVol: %i SavedVol: %i" ), int( m_MediaCtrl->GetVolume() * 100.0 ), ( int ) m_CurVolume );
m_MediaCtrl->SetEqualizer( Equalizer );
CheckFiltersEnable();
// Bind Events
m_PrevTrackButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnPrevTrackButtonClick, this );
m_NextTrackButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnNextTrackButtonClick, this );
m_PlayButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnPlayButtonClick, this );
m_StopButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnStopButtonClick, this );
m_RecordButton->Bind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnRecordButtonClick, this );
if( m_ForceGaplessButton != NULL )
m_ForceGaplessButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnForceGaplessClick, this );
if( m_VolumeButton != NULL )
{
m_VolumeButton->Bind( wxEVT_MOUSEWHEEL, &guPlayerPanel::OnVolumeMouseWheel, this );
m_VolumeButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnVolumeClicked, this );
m_VolumeButton->Bind( wxEVT_COMMAND_RIGHT_CLICK, &guPlayerPanel::OnVolumeRightClicked, this );
}
if( m_VolumeBar != NULL )
{
m_VolumeBar->Bind( wxEVT_SCROLL_CHANGED , &guPlayerPanel::OnVolumeChanged, this );
m_VolumeBar->Bind( wxEVT_SCROLL_THUMBTRACK, &guPlayerPanel::OnVolumeChanged, this );
m_VolumeBar->Bind( wxEVT_MOUSEWHEEL, &guPlayerPanel::OnVolumeMouseWheel, this );
}
//m_SmartPlayButton->Bind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnSmartPlayButtonClick, this );
m_RandomPlayButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnRandomPlayButtonClick, this );
//m_RepeatPlayButton->Bind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnRepeatPlayButtonClick, this );
if( m_EqualizerButton != NULL )
{
m_EqualizerButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnEqualizerButtonClicked, this );
m_EqualizerButton->Bind( wxEVT_COMMAND_RIGHT_CLICK, &guPlayerPanel::OnEqualizerRightButtonClicked, this );
}
m_PlayModeButton->Bind( wxEVT_BUTTON, &guPlayerPanel::OnPlayModeButtonClicked, this );
Bind( wxEVT_MENU, &guPlayerPanel::OnRandomPlayButtonClick, this, ID_PLAYER_PLAYLIST_RANDOMPLAY );
m_TitleLabel->Bind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnTitleNameDClicked, this );
m_AlbumLabel->Bind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnAlbumNameDClicked, this );
m_ArtistLabel->Bind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnArtistNameDClicked, this );
m_YearLabel->Bind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnYearDClicked, this );
m_PositionLabel->Bind( wxEVT_LEFT_UP, &guPlayerPanel::OnTimeDClicked, this );
m_Rating->Bind( guEVT_RATING_CHANGED, &guPlayerPanel::OnRatingChanged, this );
m_PlayerCoverBitmap->Bind( wxEVT_LEFT_DOWN, &guPlayerPanel::OnLeftClickPlayerCoverBitmap, this );
m_PlayerPositionSlider->Bind( wxEVT_SCROLL_THUMBTRACK, &guPlayerPanel::OnPlayerPositionSliderBeginSeek, this );
m_PlayerPositionSlider->Bind( wxEVT_SCROLL_THUMBRELEASE, &guPlayerPanel::OnPlayerPositionSliderEndSeek, this );
m_PlayerPositionSlider->Bind( wxEVT_SCROLL_CHANGED , &guPlayerPanel::OnPlayerPositionSliderChanged, this );
m_PlayerPositionSlider->Bind( wxEVT_MOUSEWHEEL, &guPlayerPanel::OnPlayerPositionSliderMouseWheel, this );
m_PlayListCtrl->Bind( wxEVT_MENU, &guPlayerPanel::OnPlayListUpdated, this, ID_PLAYER_PLAYLIST_UPDATELIST );
m_PlayListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guPlayerPanel::OnPlayListDClick, this );
Bind( guEVT_MEDIA_LOADED, &guPlayerPanel::OnMediaLoaded, this );
Bind( guEVT_MEDIA_FINISHED, &guPlayerPanel::OnMediaFinished, this );
Bind( guEVT_MEDIA_FADEOUT_FINISHED, &guPlayerPanel::OnMediaFadeOutFinished, this );
Bind( guEVT_MEDIA_FADEIN_STARTED, &guPlayerPanel::OnMediaFadeInStarted, this );
Bind( guEVT_MEDIA_TAGINFO, &guPlayerPanel::OnMediaTags, this );
Bind( guEVT_MEDIA_CHANGED_BITRATE, &guPlayerPanel::OnMediaBitrate, this );
Bind( guEVT_MEDIA_CHANGED_CODEC, &guPlayerPanel::OnMediaCodec, this );
Bind( guEVT_MEDIA_BUFFERING, &guPlayerPanel::OnMediaBuffering, this );
Bind( guEVT_MEDIA_LEVELINFO, &guPlayerPanel::OnMediaLevel, this );
Bind( guEVT_MEDIA_ERROR, &guPlayerPanel::OnMediaError, this );
Bind( guEVT_MEDIA_CHANGED_STATE, &guPlayerPanel::OnMediaState, this );
Bind( guEVT_MEDIA_CHANGED_POSITION, &guPlayerPanel::OnMediaPosition, this );
Bind( guEVT_MEDIA_CHANGED_LENGTH, &guPlayerPanel::OnMediaLength, this );
Bind( guEVT_PIPELINE_CHANGED, &guPlayerPanel::OnUpdatePipeline, this );
Bind( wxEVT_MENU, &guPlayerPanel::OnSmartAddTracks, this, ID_SMARTMODE_ADD_TRACKS );
Bind( wxEVT_MENU, &guPlayerPanel::OnSmartEndThread, this, ID_SMARTMODE_THREAD_END );
Bind( guConfigUpdatedEvent, &guPlayerPanel::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guPlayerPanel::OnCoverUpdated, this, ID_PLAYERPANEL_COVERUPDATED );
Bind( wxEVT_MENU, &guPlayerPanel::OnAddTracks, this, ID_PLAYERPANEL_ADDTRACKS );
Bind( wxEVT_MENU, &guPlayerPanel::OnRemoveTrack, this, ID_PLAYERPANEL_REMOVETRACK );
Bind( wxEVT_MENU, &guPlayerPanel::OnRepeat, this, ID_PLAYERPANEL_SETREPEAT );
Bind( wxEVT_MENU, &guPlayerPanel::OnLoop, this, ID_PLAYERPANEL_SETLOOP );
Bind( wxEVT_MENU, &guPlayerPanel::OnRandom, this, ID_PLAYERPANEL_SETRANDOM );
Bind( wxEVT_MENU, &guPlayerPanel::OnSetVolume, this, ID_PLAYERPANEL_SETVOLUME );
//
m_AudioScrobble = NULL;
if( m_AudioScrobbleEnabled )
{
m_AudioScrobble = new guAudioScrobble( m_Db );
}
}
// -------------------------------------------------------------------------------- //
guPlayerPanel::~guPlayerPanel()
{
if( m_SmartAddTracksThread )
{
m_SmartAddTracksThread->Pause();
m_SmartAddTracksThread->Delete();
}
// if( m_UpdateCoverThread )
// {
// m_UpdateCoverThread->Pause();
// m_UpdateCoverThread->Delete();
// }
if( m_AudioScrobble )
delete m_AudioScrobble;
if( m_MediaRecordCtrl )
delete m_MediaRecordCtrl;
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
Config->UnRegisterObject( this );
//printf( "guPlayerPanel::guConfig Save\n" );
//Config->WriteBool( wxT( "PlayerStopped" ), m_MediaCtrl->GetState() != guMEDIASTATE_PLAYING, CONFIG_PATH_GENERAL );
Config->WriteNum( CONFIG_KEY_GENERAL_PLAYER_VOLUME, m_LastVolume == wxNOT_FOUND ? m_CurVolume : m_LastVolume, CONFIG_PATH_GENERAL );
if( m_VolumeBar != NULL )
Config->WriteBool( CONFIG_KEY_GENERAL_PLAYER_VOLUME_VISIBLE, m_VolumeBar->IsShown(), CONFIG_PATH_GENERAL );
//Config->WriteNum( CONFIG_KEY_GENERAL_PLAYER_LOOP, m_PlayLoop, CONFIG_PATH_GENERAL );
//Config->WriteBool( CONFIG_KEY_GENERAL_PLAYER_SMART, m_PlaySmart, CONFIG_PATH_GENERAL );
Config->WriteNum( CONFIG_KEY_GENERAL_PLAYER_PLAYMODE, m_PlayMode, CONFIG_PATH_GENERAL );
// If the track length is at least the configured minimun track length save the pos offset
if( Config->ReadBool( CONFIG_KEY_GENERAL_SAVE_CURRENT_TRACK_POSITION, false, CONFIG_PATH_GENERAL ) )
{
if( ( m_LastPlayState != guMEDIASTATE_STOPPED ) &&
( m_MediaSong.m_Length >= ( unsigned int ) ( Config->ReadNum( CONFIG_KEY_GENERAL_MIN_SAVE_PLAYL_POST_LENGTH, 10, CONFIG_PATH_GENERAL ) * 60000 ) ) )
{
Config->WriteNum( CONFIG_KEY_GENERAL_CURRENT_TRACK_POS, m_LastCurPos, CONFIG_PATH_GENERAL );
}
else
{
Config->WriteNum( CONFIG_KEY_GENERAL_CURRENT_TRACK_POS, 0, CONFIG_PATH_GENERAL );
}
}
//printf( PlaySmart ? "Smart Enabled" : "Smart Disabled" ); printf( "\n" );
wxArrayInt Equalizer;
for( int index = 0; index < guEQUALIZER_BAND_COUNT; index++ )
{
Equalizer.Add( m_MediaCtrl->GetEqualizerBand( index ) );
}
Config->WriteANum( CONFIG_KEY_EQUALIZER_BAND, Equalizer, CONFIG_PATH_EQUALIZER );
Config->WriteBool( CONFIG_KEY_GENERAL_SHOW_REV_TIME, m_ShowRevTime, CONFIG_PATH_GENERAL );
Config->WriteBool( CONFIG_KEY_CROSSFADER_FORCE_GAPLESS, m_ForceGapless, CONFIG_PATH_CROSSFADER );
}
// Unbind Events
m_PrevTrackButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnPrevTrackButtonClick, this );
m_NextTrackButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnNextTrackButtonClick, this );
m_PlayButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnPlayButtonClick, this );
m_StopButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnStopButtonClick, this );
m_RecordButton->Unbind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnRecordButtonClick, this );
if( m_ForceGaplessButton != NULL )
m_ForceGaplessButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnForceGaplessClick, this );
if( m_VolumeButton != NULL )
m_VolumeButton->Unbind( wxEVT_MOUSEWHEEL, &guPlayerPanel::OnVolumeMouseWheel, this );
//m_SmartPlayButton->Unbind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnSmartPlayButtonClick, this );
m_RandomPlayButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnRandomPlayButtonClick, this );
//m_RepeatPlayButton->Unbind( wxEVT_TOGGLEBUTTON, &guPlayerPanel::OnRepeatPlayButtonClick, this );
if( m_EqualizerButton != NULL )
{
m_EqualizerButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnEqualizerButtonClicked, this );
m_EqualizerButton->Unbind( wxEVT_COMMAND_RIGHT_CLICK, &guPlayerPanel::OnEqualizerRightButtonClicked, this );
}
m_PlayModeButton->Unbind( wxEVT_BUTTON, &guPlayerPanel::OnPlayModeButtonClicked, this );
Unbind( wxEVT_MENU, &guPlayerPanel::OnRandomPlayButtonClick, this, ID_PLAYER_PLAYLIST_RANDOMPLAY );
m_TitleLabel->Unbind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnTitleNameDClicked, this );
m_AlbumLabel->Unbind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnAlbumNameDClicked, this );
m_ArtistLabel->Unbind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnArtistNameDClicked, this );
m_YearLabel->Unbind( wxEVT_LEFT_DCLICK, &guPlayerPanel::OnYearDClicked, this );
m_PositionLabel->Unbind( wxEVT_LEFT_UP, &guPlayerPanel::OnTimeDClicked, this );
m_Rating->Unbind( guEVT_RATING_CHANGED, &guPlayerPanel::OnRatingChanged, this );
m_PlayerCoverBitmap->Unbind( wxEVT_LEFT_DOWN, &guPlayerPanel::OnLeftClickPlayerCoverBitmap, this );
m_PlayerPositionSlider->Unbind( wxEVT_SCROLL_THUMBTRACK, &guPlayerPanel::OnPlayerPositionSliderBeginSeek, this );
m_PlayerPositionSlider->Unbind( wxEVT_SCROLL_THUMBRELEASE, &guPlayerPanel::OnPlayerPositionSliderEndSeek, this );
m_PlayerPositionSlider->Unbind( wxEVT_SCROLL_CHANGED , &guPlayerPanel::OnPlayerPositionSliderChanged, this );
m_PlayerPositionSlider->Unbind( wxEVT_MOUSEWHEEL, &guPlayerPanel::OnPlayerPositionSliderMouseWheel, this );
//m_PlayListCtrl->Unbind( wxEVT_MENU, &guPlayerPanel::OnPlayListUpdated, this, ID_PLAYER_PLAYLIST_UPDATELIST );
//m_PlayListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guPlayerPanel::OnPlayListDClick, this );
Unbind( guEVT_MEDIA_LOADED, &guPlayerPanel::OnMediaLoaded, this );
Unbind( guEVT_MEDIA_FINISHED, &guPlayerPanel::OnMediaFinished, this );
Unbind( guEVT_MEDIA_FADEOUT_FINISHED, &guPlayerPanel::OnMediaFadeOutFinished, this );
Unbind( guEVT_MEDIA_FADEIN_STARTED, &guPlayerPanel::OnMediaFadeInStarted, this );
Unbind( guEVT_MEDIA_TAGINFO, &guPlayerPanel::OnMediaTags, this );
Unbind( guEVT_MEDIA_CHANGED_BITRATE, &guPlayerPanel::OnMediaBitrate, this );
Unbind( guEVT_MEDIA_CHANGED_CODEC, &guPlayerPanel::OnMediaCodec, this );
Unbind( guEVT_MEDIA_BUFFERING, &guPlayerPanel::OnMediaBuffering, this );
Unbind( guEVT_MEDIA_LEVELINFO, &guPlayerPanel::OnMediaLevel, this );
Unbind( guEVT_MEDIA_ERROR, &guPlayerPanel::OnMediaError, this );
Unbind( guEVT_MEDIA_CHANGED_STATE, &guPlayerPanel::OnMediaState, this );
Unbind( guEVT_MEDIA_CHANGED_POSITION, &guPlayerPanel::OnMediaPosition, this );
Unbind( guEVT_MEDIA_CHANGED_LENGTH, &guPlayerPanel::OnMediaLength, this );
Unbind( guEVT_PIPELINE_CHANGED, &guPlayerPanel::OnUpdatePipeline, this );
Unbind( wxEVT_MENU, &guPlayerPanel::OnSmartAddTracks, this, ID_SMARTMODE_ADD_TRACKS );
Unbind( wxEVT_MENU, &guPlayerPanel::OnSmartEndThread, this, ID_SMARTMODE_THREAD_END );
Unbind( guConfigUpdatedEvent, &guPlayerPanel::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guPlayerPanel::OnCoverUpdated, this, ID_PLAYERPANEL_COVERUPDATED );
Unbind( wxEVT_MENU, &guPlayerPanel::OnAddTracks, this, ID_PLAYERPANEL_ADDTRACKS );
Unbind( wxEVT_MENU, &guPlayerPanel::OnRemoveTrack, this, ID_PLAYERPANEL_REMOVETRACK );
Unbind( wxEVT_MENU, &guPlayerPanel::OnRepeat, this, ID_PLAYERPANEL_SETREPEAT );
Unbind( wxEVT_MENU, &guPlayerPanel::OnLoop, this, ID_PLAYERPANEL_SETLOOP );
Unbind( wxEVT_MENU, &guPlayerPanel::OnRandom, this, ID_PLAYERPANEL_SETRANDOM );
Unbind( wxEVT_MENU, &guPlayerPanel::OnSetVolume, this, ID_PLAYERPANEL_SETVOLUME );
if( m_MediaCtrl )
delete m_MediaCtrl;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
guConfig * Config = NULL;
bool MediaCtrlNeedUpdated = false;
if( Flags & guPREFERENCE_PAGE_FLAG_PLAYBACK )
{
Config = ( guConfig * ) guConfig::Get();
//guLogDebug( wxT( "Reading PlayerPanel Config Updated" ) );
m_PlayRandom = Config->ReadBool( CONFIG_KEY_GENERAL_RANDOM_PLAY_ON_EMPTY_PLAYLIST, false, CONFIG_PATH_GENERAL );
m_PlayRandomMode = Config->ReadNum( CONFIG_KEY_GENERAL_RANDOM_MODE_ON_EMPTY_PLAYLIST, guRANDOM_MODE_TRACK, CONFIG_PATH_GENERAL );
m_ShowNotifications = Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_NOTIFICATIONS, true, CONFIG_PATH_GENERAL );
m_ShowNotificationsTime = Config->ReadNum( CONFIG_KEY_GENERAL_NOTIFICATION_TIME, 0, CONFIG_PATH_GENERAL );
if( m_EnableEq != Config->ReadBool( CONFIG_KEY_GENERAL_EQ_ENABLED, true, CONFIG_PATH_GENERAL ) )
OnEqualizerRightButtonClicked( event );
if( m_EnableVolCtls != Config->ReadBool( CONFIG_KEY_GENERAL_VOLUME_ENABLED, true, CONFIG_PATH_GENERAL ) )
OnVolCtlToggle( event );
m_SmartPlayAddTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_NUM_TRACKS_TO_ADD, 3, CONFIG_PATH_PLAYBACK );
m_SmartPlayMinTracksToPlay = Config->ReadNum( CONFIG_KEY_PLAYBACK_MIN_TRACKS_PLAY, 4, CONFIG_PATH_PLAYBACK );
m_DelTracksPlayed = Config->ReadBool( CONFIG_KEY_PLAYBACK_DEL_TRACKS_PLAYED, false, CONFIG_PATH_PLAYBACK );
m_SmartMaxArtistsList = Config->ReadNum( CONFIG_KEY_PLAYBACK_SMART_FILTER_ARTISTS, 20, CONFIG_PATH_PLAYBACK );
m_SmartMaxTracksList = Config->ReadNum( CONFIG_KEY_PLAYBACK_SMART_FILTER_TRACKS, 100, CONFIG_PATH_PLAYBACK );
// We only insert the last CACHEITEMS as the rest should be forgiven
while( ( int ) m_SmartAddedTracks.Count() > m_SmartMaxTracksList )
m_SmartAddedTracks.RemoveAt( 0 );
while( ( int ) m_SmartAddedArtists.Count() > m_SmartMaxArtistsList )
m_SmartAddedArtists.RemoveAt( 0 );
m_SilenceDetector = Config->ReadBool( CONFIG_KEY_PLAYBCK_SILENCE_DETECTOR, false, CONFIG_PATH_PLAYBACK );
m_SilenceDetectorLevel = Config->ReadNum( CONFIG_KEY_PLAYBCK_SILENCE_LEVEL, -55, CONFIG_PATH_PLAYBACK );
if( Config->ReadBool( CONFIG_KEY_PLAYBCK_SILENCE_AT_END, false, CONFIG_PATH_PLAYBACK ) )
{
m_SilenceDetectorTime = Config->ReadNum( CONFIG_KEY_PLAYBCK_SILENCE_END_TIME, 45, CONFIG_PATH_PLAYBACK ) * 1000;
}
MediaCtrlNeedUpdated = true;
}
if( Flags & guPREFERENCE_PAGE_FLAG_RECORD )
{
if( !Config )
Config = ( guConfig * ) guConfig::Get();
m_RecordButton->Show( Config->ReadBool( CONFIG_KEY_RECORD_ENABLED, false, CONFIG_PATH_RECORD ) );
Layout();
if( m_MediaRecordCtrl )
{
m_MediaRecordCtrl->UpdatedConfig();
}
}
if( Flags & guPREFERENCE_PAGE_FLAG_CROSSFADER )
{
if( !Config )
Config = ( guConfig * ) guConfig::Get();
m_ForceGapless = Config->ReadBool( CONFIG_KEY_CROSSFADER_FORCE_GAPLESS, false, CONFIG_PATH_CROSSFADER );
m_FadeOutTime = Config->ReadNum( CONFIG_KEY_CROSSFADER_FADEOUT_TIME, 50, CONFIG_PATH_CROSSFADER ) * 100;
MediaCtrlNeedUpdated = true;
}
if( Flags & guPREFERENCE_PAGE_FLAG_AUDIOSCROBBLE )
{
if( !Config )
Config = ( guConfig * ) guConfig::Get();
m_AudioScrobbleEnabled = Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM ) ||
Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM );
if( m_AudioScrobbleEnabled )
{
if( !m_AudioScrobble )
m_AudioScrobble = new guAudioScrobble( m_Db );
else
m_AudioScrobble->OnConfigUpdated();
}
else
{
wxCommandEvent event( wxEVT_MENU, ID_AUDIOSCROBBLE_UPDATED );
event.SetInt( 1 );
wxPostEvent( m_MainFrame, event );
}
}
if( m_MediaCtrl && MediaCtrlNeedUpdated )
{
m_MediaCtrl->UpdatedConfig();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetArtistLabel( const wxString &artistname )
{
// wxString Label = artistname;
// Label.Replace( wxT( "&" ), wxT( "&&" ) );
m_ArtistLabel->SetLabel( artistname );
m_ArtistLabel->SetToolTip( artistname );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetAlbumLabel( const wxString &albumname )
{
// wxString Label = albumname;
// Label.Replace( wxT( "&" ), wxT( "&&" ) );
m_AlbumLabel->SetLabel( albumname );
m_AlbumLabel->SetToolTip( albumname );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetTitleLabel( const wxString &trackname )
{
// wxString Label = trackname;
// Label.Replace( wxT( "&" ), wxT( "&&" ) );
m_TitleLabel->SetLabel( trackname );
m_TitleLabel->SetToolTip( trackname );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetRatingLabel( const int rating )
{
m_Rating->SetRating( rating );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetRating( const int rating )
{
//m_MediaSong.m_Rating = rating;
m_Rating->SetRating( rating );
guRatingEvent Event;
Event.SetInt( rating );
OnRatingChanged( Event );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdatePositionLabel( const unsigned int curpos )
{
wxString Label;
unsigned int CurLen = m_LastLength;
//if( !m_ShowRevTime || !m_MediaSong.m_Length )
if( !m_ShowRevTime || !CurLen )
{
Label = LenToString( curpos );
}
else if( CurLen )
{
// The Gapless playback can produce than while we are listenning to the finish of
// a track the player already changed to the next track.
// To avoid weird time less results we check if the length of the track is
// bigger than the current pos.
//if( curpos > m_MediaSong.m_Length )
if( curpos > CurLen )
//Label = wxT( "-" ) + LenToString( m_MediaSong.m_Length );
Label = wxT( "-" ) + LenToString( CurLen );
else
Label = wxT( "-" ) + LenToString( CurLen - curpos );
}
//if( m_MediaSong.m_Length )
if( m_LastLength )
{
//Label += wxT( " / " ) + LenToString( m_MediaSong.m_Length );
Label += wxT( " / " ) + LenToString( CurLen );
}
m_PositionLabel->SetLabel( Label );
m_PosLabelSizer->Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetCodecLabel( const wxString &codec, const wxString &tooltip )
{
//guLogDebug( wxT( "SetFormatLabel( %s )" ), codec.c_str() );
m_CodecLabel->SetLabel( wxString::Format( wxT( "[%s]" ), codec.c_str() ) );
m_CodecLabel->SetToolTip( tooltip );
m_BitRateSizer->Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetBitRateLabel( int bitrate )
{
//guLogDebug( wxT( "SetBitRateLabel( %i )" ), bitrate );
if( bitrate )
{
m_BitRateLabel->SetLabel( wxString::Format( wxT( "[%ukbps]" ), bitrate ) );
}
else
m_BitRateLabel->SetLabel( wxT( "[kbps]" ) );
m_BitRateSizer->Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetBitRate( int bitrate )
{
if( bitrate )
{
bitrate = bitrate / 1000;
//guLogDebug( wxT( "Bitrate: %u" ), bitrate );
m_BitRateLabel->SetLabel( wxString::Format( wxT( "[%ukbps]" ), bitrate ) );
if( ( m_MediaSong.m_Bitrate < bitrate ) && ( GetState() == guMEDIASTATE_PLAYING ) )
{
m_MediaSong.m_Bitrate = bitrate;
if( m_MediaSong.m_MediaViewer )
{
guDbLibrary * Db = m_MediaSong.m_MediaViewer->GetDb();
Db->UpdateTrackBitRate( m_MediaSong.m_SongId, bitrate );
}
// Update the track in database, playlist, etc
m_MainFrame->UpdatedTrack( guUPDATED_TRACKS_PLAYER, &m_MediaSong );
}
}
else
m_BitRateLabel->SetLabel( wxT( "[kbps]" ) );
m_BitRateSizer->Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetCodec( const wxString &codec )
{
wxString Tooltip = codec.Lower();
wxString AudioCodec = "other";
if( Tooltip.Contains( "mp3" ) )
{
AudioCodec = "mp3";
}
else if( Tooltip.Contains( "aac" ) )
{
AudioCodec = "aac";
}
else if( Tooltip.Contains( "vorbis" ) )
{
AudioCodec = "ogg";
}
else if( Tooltip.Contains( "wma" ) )
{
AudioCodec = "wma";
}
else if( Tooltip.Contains( "flac" ) )
{
AudioCodec = "flac";
}
else if( Tooltip.Contains( "monkey" ) )
{
AudioCodec = "ape";
}
else if( Tooltip.Contains( "apple lossless" ) )
{
AudioCodec = "m4a";
}
else if( Tooltip.Contains( "musepack" ) )
{
AudioCodec = "mpc";
}
SetCodecLabel( AudioCodec, Tooltip );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetPlayList( const guTrackArray &SongList )
{
wxCommandEvent event;
m_PlayListCtrl->SetPlayList( SongList );
SetNextTrack( m_PlayListCtrl->GetCurrent() );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
TrackListChanged();
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
if( m_SmartAddTracksThread )
{
m_SmartAddTracksThread->Pause();
m_SmartAddTracksThread->Delete();
m_SmartAddTracksThread = NULL;
m_SmartSearchEnabled = false;
}
// Reset the Smart played items
m_SmartAddedTracks.Empty();
m_SmartAddedArtists.Empty();
//guLogDebug( wxT( "SetPlayList adding track to smart cache..." ) );
int Index = 0;
int Count = SongList.Count();
// We only insert the last CACHEITEMS as the rest should be forgiven
if( Count > m_SmartMaxTracksList )
Index = Count - m_SmartMaxTracksList;
for( ; Index < Count; Index++ )
{
m_SmartAddedTracks.Add( SongList[ Index ].m_SongId );
}
Index = 0;
if( Count > m_SmartMaxArtistsList )
Index = Count - m_SmartMaxArtistsList;
for( ; Index < Count; Index++ )
{
m_SmartAddedArtists.Add( SongList[ Index ].m_ArtistName.Upper() );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetPlayList( const wxArrayString &files )
{
m_PlayListCtrl->ClearItems();
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_PlayListCtrl->AddPlayListItem( files[ Index ], guINSERT_AFTER_CURRENT_NONE, wxNOT_FOUND );
}
m_PlayListCtrl->ReloadItems();
if( m_PlayListCtrl->GetItemCount() )
{
m_PlayListCtrl->SetCurrent( 0 );
SetNextTrack( m_PlayListCtrl->GetCurrent() );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
TrackListChanged();
// Add the added track to the smart cache
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
if( m_SmartAddTracksThread )
{
m_SmartAddTracksThread->Pause();
m_SmartAddTracksThread->Delete();
m_SmartAddTracksThread = NULL;
m_SmartSearchEnabled = false;
}
// Reset the Smart played items
m_SmartAddedTracks.Empty();
m_SmartAddedArtists.Empty();
//guLogDebug( wxT( "SetPlayList adding track to smart cache..." ) );
int Count;
int Index = 0;
Count = m_PlayListCtrl->GetItemCount();
// We only insert the last CACHEITEMS as the rest should be forgiven
if( Count > m_SmartMaxTracksList )
Index = Count - m_SmartMaxTracksList;
for( ; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
m_SmartAddedTracks.Add( Track->m_SongId );
}
Index = 0;
if( Count > m_SmartMaxArtistsList )
Index = Count - m_SmartMaxArtistsList;
for( ; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
m_SmartAddedArtists.Add( Track->m_ArtistName.Upper() );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::AddToPlayList( const guTrackArray &tracks, const bool allowplay, const int aftercurrent )
{
int PrevTrackCount = m_PlayListCtrl->GetCount();
if( tracks.Count() )
{
guTrack * Track = &tracks[ 0 ];
bool ClearPlayList = ( Track->m_TrackMode == guTRACK_MODE_RANDOM ||
Track->m_TrackMode == guTRACK_MODE_SMART ) && !m_DelTracksPlayed;
m_PlayListCtrl->AddToPlayList( tracks, ClearPlayList, aftercurrent );
TrackListChanged();
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
int Count = tracks.Count();
// We only insert the last CACHEITEMS as the rest should be forgiven
for( int Index = 0; Index < Count; Index++ )
{
if( tracks[ Index ].m_TrackMode != guTRACK_MODE_SMART )
{
m_SmartAddedTracks.Add( tracks[ Index ].m_SongId );
m_SmartAddedArtists.Add( tracks[ Index ].m_ArtistName.Upper() );
}
}
if( ( Count = m_SmartAddedTracks.Count() ) > m_SmartMaxTracksList )
m_SmartAddedTracks.RemoveAt( 0, Count - m_SmartMaxTracksList );
if( ( Count = m_SmartAddedArtists.Count() ) > m_SmartMaxArtistsList )
m_SmartAddedArtists.RemoveAt( 0, Count - m_SmartMaxArtistsList );
}
// Change vehaivour to start playing when its not playing
if( allowplay && !PrevTrackCount && ( GetState() != guMEDIASTATE_PLAYING ) )
{
wxCommandEvent CmdEvent;
OnNextTrackButtonClick( CmdEvent );
OnPlayButtonClick( CmdEvent );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::AddToPlayList( const wxString &FileName, const int aftercurrent )
{
int PrevTrackCount = m_PlayListCtrl->GetCount();
m_PlayListCtrl->AddPlayListItem( FileName, aftercurrent, wxNOT_FOUND );
m_PlayListCtrl->ReloadItems();
TrackListChanged();
// Add the added track to the smart cache
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
int Count = m_PlayListCtrl->GetCount();
// TODO : Check if the track was really added or not
if( Count > PrevTrackCount )
{
guTrack * Track = m_PlayListCtrl->GetItem( Count - 1 );
m_SmartAddedTracks.Add( Track->m_SongId );
m_SmartAddedArtists.Add( Track->m_ArtistName.Upper() );
if( ( int ) m_SmartAddedTracks.Count() > m_SmartMaxTracksList )
m_SmartAddedTracks.RemoveAt( 0 );
if( ( int ) m_SmartAddedArtists.Count() > m_SmartMaxArtistsList )
m_SmartAddedArtists.RemoveAt( 0 );
}
}
if( !PrevTrackCount && m_PlayListCtrl->GetCount() && ( GetState() != guMEDIASTATE_PLAYING ) )
{
wxCommandEvent CmdEvent;
OnNextTrackButtonClick( CmdEvent );
OnPlayButtonClick( CmdEvent );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::AddToPlayList( const wxArrayString &files, const int aftercurrent )
{
int PrevTrackCount = m_PlayListCtrl->GetItemCount();
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_PlayListCtrl->AddPlayListItem( files[ Index ], aftercurrent, aftercurrent ? Index : wxNOT_FOUND );
}
m_PlayListCtrl->ReloadItems();
TrackListChanged();
// Add the added track to the smart cache
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
Count = m_PlayListCtrl->GetItemCount();
// We only insert the last CACHEITEMS as the rest should be forgiven
for( int Index = 0; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
if( m_SmartAddedTracks.Index( Track->m_SongId ) == wxNOT_FOUND )
m_SmartAddedTracks.Add( Track->m_SongId );
if( m_SmartAddedArtists.Index( Track->m_ArtistName.Upper() ) == wxNOT_FOUND )
m_SmartAddedArtists.Add( Track->m_ArtistName.Upper() );
}
if( ( Count = m_SmartAddedTracks.Count() ) > m_SmartMaxTracksList )
m_SmartAddedTracks.RemoveAt( 0, Count - m_SmartMaxTracksList );
if( ( Count = m_SmartAddedArtists.Count() ) > m_SmartMaxArtistsList )
m_SmartAddedArtists.RemoveAt( 0, Count - m_SmartMaxArtistsList );
}
if( !PrevTrackCount && m_PlayListCtrl->GetItemCount() && ( GetState() != guMEDIASTATE_PLAYING ) )
{
wxCommandEvent CmdEvent;
OnNextTrackButtonClick( CmdEvent );
OnPlayButtonClick( CmdEvent );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::AddToPlayList( const wxArrayString &files, const bool allowplay, const int aftercurrent )
{
guLogDebug( wxT( "AddToPlayList( ..., %i, %i )" ), allowplay, aftercurrent );
int PrevTrackCount = m_PlayListCtrl->GetItemCount();
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_PlayListCtrl->AddPlayListItem( files[ Index ], aftercurrent, Index );
}
m_PlayListCtrl->ReloadItems();
TrackListChanged();
// Add the added track to the smart cache
if( m_PlayMode == guPLAYER_PLAYMODE_SMART )
{
Count = m_PlayListCtrl->GetItemCount();
// We only insert the last CACHEITEMS as the rest should be forgiven
for( int Index = 0; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
if( m_SmartAddedTracks.Index( Track->m_SongId ) == wxNOT_FOUND )
m_SmartAddedTracks.Add( Track->m_SongId );
if( m_SmartAddedArtists.Index( Track->m_ArtistName.Upper() ) == wxNOT_FOUND )
m_SmartAddedArtists.Add( Track->m_ArtistName.Upper() );
}
if( ( Count = m_SmartAddedTracks.Count() ) > m_SmartMaxTracksList )
m_SmartAddedTracks.RemoveAt( 0, Count - m_SmartMaxTracksList );
if( ( Count = m_SmartAddedArtists.Count() ) > m_SmartMaxArtistsList )
m_SmartAddedArtists.RemoveAt( 0, Count - m_SmartMaxArtistsList );
}
if( allowplay && ( m_PlayListCtrl->GetCount() > PrevTrackCount ) && ( GetState() != guMEDIASTATE_PLAYING ) )
{
wxCommandEvent CmdEvent;
CmdEvent.SetInt( PrevTrackCount );
OnPlayListDClick( CmdEvent );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::TrackListChanged( void )
{
// m_PlayListLenStaticText->SetLabel( m_PlayListCtrl->GetLengthStr() );
// m_PlayListLabelsSizer->Layout();
// m_PlayListCtrl->SetColumnLabel( 0, _( "Now Playing" ) +
// wxString::Format( wxT( ": %i / %li ( %s )" ),
// m_PlayListCtrl->GetCurItem() + 1,
// m_PlayListCtrl->GetCount(),
// m_PlayListCtrl->GetLengthStr().c_str() ) );
wxCommandEvent TitleEvent( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATETITLE );
wxPostEvent( m_MainFrame, TitleEvent );
wxCommandEvent TracksChangedEvent( wxEVT_MENU, ID_PLAYERPANEL_TRACKLISTCHANGED );
wxPostEvent( this, TracksChangedEvent );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayListUpdated( wxCommandEvent &event )
{
m_PlayListCtrl->ReloadItems();
//SetNextTrack( m_PlayListCtrl->GetCurrent() );
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
// If a Player reset is needed
if( event.GetExtraLong() && ( m_MediaCtrl->GetState() != guMEDIASTATE_PLAYING ) )
{
//OnStopButtonClick( event );
//OnPlayButtonClick( event );
if( m_PlayListCtrl->GetCount() )
{
event.SetInt( 0 );
OnPlayListDClick( event );
}
}
if( ( event.GetExtraLong() || event.GetInt() ) &&
( m_PlayMode == guPLAYER_PLAYMODE_SMART ) )
{
if( m_SmartAddTracksThread )
{
m_SmartAddTracksThread->Pause();
m_SmartAddTracksThread->Delete();
m_SmartAddTracksThread = NULL;
m_SmartSearchEnabled = false;
}
// Reset the Smart added songs cache
m_SmartAddedTracks.Empty();
m_SmartAddedArtists.Empty();
int Count;
int Index = 0;
Count = m_PlayListCtrl->GetCount();
// We only insert the last CACHEITEMS as the rest should be forgiven
if( Count > m_SmartMaxTracksList )
Index = Count - m_SmartMaxTracksList;
for( ; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
m_SmartAddedTracks.Add( Track->m_SongId );
}
Index = 0;
Count = m_PlayListCtrl->GetCount();
if( Count > m_SmartMaxArtistsList )
Index = Count - m_SmartMaxArtistsList;
for( ; Index < Count; Index++ )
{
guTrack * Track = m_PlayListCtrl->GetItem( Index );
m_SmartAddedArtists.Add( Track->m_ArtistName.Upper() );
}
}
TrackListChanged();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnSmartEndThread( wxCommandEvent &event )
{
m_SmartAddTracksThread = NULL;
m_SmartSearchEnabled = false;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnSmartAddTracks( wxCommandEvent &event )
{
guTrackArray * Tracks = ( guTrackArray * ) event.GetClientData();
if( Tracks )
{
//guLogMessage( wxT( "Tracks %i" ), Tracks->Count() );
if( Tracks->Count() )
{
AddToPlayList( * Tracks );
}
delete Tracks;
}
m_SmartSearchEnabled = false;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SmartAddTracks( const guTrack &CurSong )
{
// if its already searching
if( m_SmartSearchEnabled )
return;
m_SmartSearchEnabled = true;
m_SmartAddTracksThread = new guSmartModeThread( CurSong.m_MediaViewer ? CurSong.m_MediaViewer->GetDb() : m_Db, this,
CurSong.m_ArtistName, CurSong.m_SongName,
&m_SmartAddedTracks, &m_SmartAddedArtists,
m_SmartMaxTracksList, m_SmartMaxArtistsList,
m_SmartPlayAddTracks, guSMARTMODE_TRACK_LIMIT_TRACKS,
m_PlayerFilters->GetAllowFilterId(),
m_PlayerFilters->GetDenyFilterId() );
}
// -------------------------------------------------------------------------------- //
int guPlayerPanel::GetCurrentItem()
{
return m_PlayListCtrl->GetCurItem();
}
// -------------------------------------------------------------------------------- //
int guPlayerPanel::GetItemCount()
{
return m_PlayListCtrl->GetItemCount();
}
// -------------------------------------------------------------------------------- //
const guTrack * guPlayerPanel::GetTrack( int index )
{
return m_PlayListCtrl->GetItem( index );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::RemoveItem( int itemnum )
{
m_PlayListCtrl->RemoveItem( itemnum );
m_PlayListCtrl->ReloadItems();
}
// -------------------------------------------------------------------------------- //
int guPlayerPanel::GetCaps()
{
return m_PlayListCtrl->GetCaps();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetNextTrack( const guTrack * Song )
{
guLogDebug( wxT( "SetNextTrack: %i" ), m_PlayListCtrl->GetCurItem() );
if( !Song )
return;
m_NextSong = * Song;
//m_NextTrackId = true;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayListDClick( wxCommandEvent &event )
{
int item = event.GetInt();
m_PlayListCtrl->SetCurrent( item, m_DelTracksPlayed && !GetPlayLoop() );
SetNextTrack( m_PlayListCtrl->GetCurrent() );
//wxLogMessage( wxT( "Selected %i : %s - %s" ), m_MediaSong.SongId, m_MediaSong.ArtistName.c_str(), m_MediaSong.SongName.c_str() );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::LoadMedia( guFADERPLAYBIN_PLAYTYPE playtype, const bool forceskip )
{
guLogDebug( wxT( "LoadMedia %li %li (%i)" ), m_CurTrackId, m_NextTrackId, m_SavedPlayedTrack );
if( !forceskip && ( m_MediaSong.m_Type & guTRACK_TYPE_STOP_HERE ) )
{
m_MediaSong.m_Type = guTrackType( int( m_MediaSong.m_Type ) ^ guTRACK_TYPE_STOP_HERE );
m_PlayListCtrl->ClearStopAtEnd();
return;
}
guLogDebug( wxT( "LoadMedia Cur: %i %i starting at %i" ), m_PlayListCtrl->GetCurItem(), playtype, m_NextSong.m_Offset );
//m_MediaCtrl->Load( NextItem->FileName );
const char *fn_uri, *param = (const char*)m_NextSong.m_FileName.mb_str();
if( gst_uri_is_valid( param ) )
fn_uri = param;
else
fn_uri = gst_filename_to_uri( param, NULL );
wxString Uri = wxString( fn_uri );
try {
if( ( playtype == guFADERPLAYBIN_PLAYTYPE_AFTER_EOS ) && ( m_MediaSong.m_Offset || m_NextSong.m_Offset ) )
{
playtype = guFADERPLAYBIN_PLAYTYPE_REPLACE;
}
//guLogDebug( wxT( "'%s'\n'%s'" ), FileName.c_str(), FileNameEncode( Uri ).c_str() );
m_NextTrackId = m_MediaCtrl->Load( Uri, playtype, m_NextSong.m_Offset + m_TrackStartPos );
if( m_TrackStartPos )
{
m_TrackStartPos = 0;
}
if( !m_NextTrackId )
{
guLogError( wxT( "ee: Failed load of file '%s'" ), Uri.c_str() );
int CurItem = m_PlayListCtrl->GetCurItem();
wxCommandEvent event;
event.SetId( ID_PLAYERPANEL_NEXTTRACK );
event.SetInt( playtype );
wxPostEvent( this, event );
//m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
RemoveItem( CurItem );
}
}
catch(...)
{
guLogError( wxT( "Error loading '%s'" ), m_NextSong.m_FileName.c_str() );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaBuffering( guMediaEvent &event )
{
wxCommandEvent GaugeEvent( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
int Percent = event.GetInt();
// printf( "Buffering: %d%%\n", Percent );
if( Percent == 100 )
{
if( m_BufferGaugeId != wxNOT_FOUND )
{
GaugeEvent.SetId( ID_STATUSBAR_GAUGE_REMOVE );
GaugeEvent.SetInt( m_BufferGaugeId );
wxPostEvent( m_MainFrame, GaugeEvent );
m_BufferGaugeId = wxNOT_FOUND;
}
}
else
{
if( m_BufferGaugeId == wxNOT_FOUND )
{
m_BufferGaugeId = ( ( guStatusBar * ) m_MainFrame->GetStatusBar() )->AddGauge( _( "Buffering..." ) );
GaugeEvent.SetId( ID_STATUSBAR_GAUGE_SETMAX );
GaugeEvent.SetInt( m_BufferGaugeId );
GaugeEvent.SetExtraLong( 100 );
wxPostEvent( m_MainFrame, GaugeEvent );
}
if( m_BufferGaugeId != wxNOT_FOUND )
{
GaugeEvent.SetId( ID_STATUSBAR_GAUGE_UPDATE );
GaugeEvent.SetInt( m_BufferGaugeId );
GaugeEvent.SetExtraLong( Percent );
wxPostEvent( m_MainFrame, GaugeEvent );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaLevel( guMediaEvent &event )
{
guLevelInfo * LevelInfo = ( guLevelInfo * ) event.GetClientObject();
// We only enable to check if :
// * Already not detected
// * Its enabled in preferences
// * Its not a radiostation
// * Not enabled a time range or
// * TrackLength bigger in 10 secs of the minimun time range
if( !m_SilenceDetected && m_SilenceDetector &&
( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION ) &&
( !m_SilenceDetectorTime ||
( m_MediaSong.m_Length > ( unsigned int ) ( m_SilenceDetectorTime + 10000 ) ) ) )
{
//guLogDebug( wxT( "Decay Level: %0.2f / %02i %s %li > %li" ), LevelInfo->m_Decay_L, m_SilenceDetectorLevel, LenToString( ( unsigned int ) ( m_LastCurPos / 1000 ) ).c_str(), m_MediaSong.m_Length * 1000, ( unsigned int ) ( m_SilenceDetectorTime + 10000 ) );
if( LevelInfo->m_Decay_L < double( m_SilenceDetectorLevel ) )
{
unsigned long EventTime = m_LastCurPos; //LevelInfo->m_EndTime;
if( EventTime > 10000 )
{
unsigned long TrackLength = m_MediaSong.m_Length;
//guLogDebug( wxT( "The level is now lower than triger level" ) );
//guLogDebug( wxT( "(%f) %02i : %li , %i, %i" ), LevelInfo->m_Decay_L, m_SilenceDetectorLevel, EventTime, TrackLength - EventTime, m_SilenceDetectorTime );
//guLogDebug( wxT( "(%li) %f %02i : %li , %i, %i" ), event.GetExtraLong(), LevelInfo->m_Decay_L, m_SilenceDetectorLevel, EventTime, TrackLength - EventTime, m_SilenceDetectorTime );
// We only skip to next track if the level is lower than the triger one and also if
// we are at the end time period (if configured this way) and the time left is more than 500msecs
if( !m_TrackChanged && !m_NextTrackId && ( m_CurTrackId == event.GetExtraLong() ) &&
( !m_SilenceDetectorTime || ( ( ( unsigned int ) m_SilenceDetectorTime > ( TrackLength - EventTime ) ) &&
( ( EventTime + 500 ) < TrackLength ) ) ) )
{
m_SilenceDetected = true;
//guLogDebug( wxT( "Silence detected. Changed to next track %i" ), m_PlayListCtrl->GetCurItem() );
wxCommandEvent evt;
evt.SetId( ID_PLAYERPANEL_NEXTTRACK );
OnNextTrackButtonClick( evt );
}
}
}
}
if( m_PlayerVumeters )
{
//guLogDebug( wxT( "%lli %lli (%lli)" ), LevelInfo->m_EndTime, LevelInfo->m_OutTime, LevelInfo->m_OutTime - LevelInfo->m_EndTime );
m_PlayerVumeters->SetLevels( * LevelInfo );
// guLogDebug( wxT( "L:%02.02f R:%02.02f" ),
// event.m_LevelInfo.m_Peak_L,
// event.m_LevelInfo.m_Peak_R );
}
delete LevelInfo;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaError( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaError: %i" ), m_PlayListCtrl->GetCurItem() );
wxString * ErrorStr = ( wxString * ) event.GetClientData();
if( ErrorStr )
{
m_NotifySrv->Notify( wxEmptyString, wxT( "Guayadeque: GStreamer Error" ), * ErrorStr, NULL );
delete ErrorStr;
}
else
{
m_NotifySrv->Notify( wxEmptyString, wxT( "Guayadeque: GStreamer Error" ), _( "Unknown" ), NULL );
}
if( m_MediaCtrl->GetState() == guMEDIASTATE_PLAYING )
m_ErrorFound = true;
m_MediaCtrl->ClearError();
int CurItem = m_PlayListCtrl->GetCurItem();
m_NextTrackId = 0;
wxCommandEvent CmdEvent;
CmdEvent.SetInt( guFADERPLAYBIN_PLAYTYPE_REPLACE );
OnNextTrackButtonClick( CmdEvent );
RemoveItem( CurItem );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaState( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaState: %i %li %li" ), event.GetInt(), m_CurTrackId, m_NextTrackId );
GstState State = ( GstState ) event.GetInt();
if( State == GST_STATE_PLAYING && m_NextTrackId )
{
OnMediaPlayStarted();
}
if( State != m_LastPlayState )
{
if( State == GST_STATE_PLAYING ) //guMEDIASTATE_PLAYING )
{
m_PlayButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_pause ) );
m_PlayButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_pause ) );
}
else
{
m_PlayButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_play ) );
m_PlayButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_play ) );
if( State == GST_STATE_READY )
{
UpdatePositionLabel( 0 );
m_PlayerPositionSlider->SetValue( 0 );
}
}
m_PlayButton->Refresh();
m_LastPlayState = State;
//
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_STATUSCHANGED );
wxPostEvent( m_MainFrame, event );
}
if( m_ErrorFound )
{
m_ErrorFound = false;
wxCommandEvent CmdEvent;
OnNextTrackButtonClick( CmdEvent );
OnPlayButtonClick( CmdEvent );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaPosition( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaPosition... %i / %i - %li" ), event.GetInt(), m_MediaSong.m_Offset, event.GetExtraLong() );
if( ( event.GetInt() < 0 ) || ( event.GetInt() < ( int ) m_MediaSong.m_Offset ) )
return;
long EventId = ( long ) event.GetClientData();
if( EventId != m_CurTrackId )
return;
wxFileOffset CurPos = event.GetInt() - m_MediaSong.m_Offset;
wxFileOffset CurLen = event.GetExtraLong();
if( !m_MediaSong.m_Offset )
{
if( CurLen && ( CurLen != m_LastLength ) )
{
m_LastLength = CurLen;
if( !m_LastLength )
m_PlayerPositionSlider->SetValue( 0 );
// Some track lengths are not correctly read by taglib so
// we try to find the length from gstreamer and update the database
// We need to not do this for radiostations or online streams
if( CurLen > 0 && m_MediaSong.m_Length == 0 &&
m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION )
{
m_MediaSong.m_Length = CurLen;
if( m_MediaSong.m_SongId )
{
if( m_MediaSong.m_MediaViewer )
{
guDbLibrary * Db = m_MediaSong.m_MediaViewer->GetDb();
Db->UpdateTrackLength( m_MediaSong.m_SongId, m_MediaSong.m_Length );
}
else if( m_MediaSong.m_Type == guTRACK_TYPE_PODCAST )
{
guDbPodcasts * DbPodcasts = m_MainFrame->GetPodcastsDb();
DbPodcasts->UpdatePodcastItemLength( m_MediaSong.m_SongId, m_MediaSong.m_Length );
}
}
// Update the track in database, playlist, etc
m_MainFrame->UpdatedTrack( guUPDATED_TRACKS_PLAYER, &m_MediaSong );
}
}
}
else
{
if( m_LastLength != m_MediaSong.m_Length )
m_LastLength = m_MediaSong.m_Length;
}
if( ( ( CurPos / 1000 ) != ( m_LastCurPos / 1000 ) ) && !m_SliderIsDragged )
{
guLogDebug( wxT( "OnMediaPosition... %li - %li => %li %li %li" ), CurPos, CurLen, m_LastLength - CurPos, m_CurTrackId, m_NextTrackId );
m_LastCurPos = CurPos;
if( m_TrackChanged )
m_TrackChanged = false;
UpdatePositionLabel( CurPos );
if( m_LastLength )
{
m_PlayerPositionSlider->SetValue( CurPos / ( m_LastLength / 1000 ) );
}
m_MediaSong.m_PlayTime = CurPos;
if( !m_AboutToEndDetected &&
!m_NextTrackId &&
( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION ) &&
( CurPos > 0 ) && ( m_LastLength > 0 ) &&
( ( CurPos + 4000 + ( !m_ForceGapless ? m_FadeOutTime : 0 ) ) >= m_LastLength )
)
{
//if( !m_ForceGapless && m_FadeOutTime && !m_MediaSong.m_Offset && ( GetState() == guMEDIASTATE_PLAYING ) )
if( ( !( m_ForceGapless || !m_FadeOutTime ) || !m_MediaSong.m_Offset ) && ( GetState() == guMEDIASTATE_PLAYING ) )
{
m_AboutToEndDetected = true;
guLogDebug( wxT( "Detected about to finish track... Trying to load the next track..." ) );
wxCommandEvent evt;
OnNextTrackButtonClick( evt );
}
}
}
//
// If we are in gapless mode with cue tracks only skip once we reach the end of the track.
if( m_MediaSong.m_Offset && ( m_ForceGapless || !m_FadeOutTime ) && ( ( CurPos + 250 ) >= m_LastLength ) )
{
guLogDebug( wxT( "Track should finish now..." ) );
wxCommandEvent evt;
OnNextTrackButtonClick( evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaLength( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaLength... %i" ), event.GetInt() );
if( m_MediaSong.m_Offset )
return;
wxFileOffset CurLen = event.GetInt();
if( CurLen != m_LastLength )
{
m_LastLength = CurLen;
UpdatePositionLabel( m_LastCurPos );
m_MediaSong.m_Length = CurLen;
}
}
// -------------------------------------------------------------------------------- //
void ExtractMetaData( wxString &title, wxString &artist, wxString &trackname )
{
int FindPos;
if( !title.IsEmpty() )
{
FindPos = title.Find( wxT( " - " ) );
if( FindPos == wxNOT_FOUND )
FindPos = title.Find( wxT( "_-_" ) );
if( FindPos != wxNOT_FOUND )
{
artist = title.Mid( 0, FindPos );
title = title.Mid( FindPos + 3 );
FindPos = title.Find( wxT( " - " ) );
if( FindPos == wxNOT_FOUND )
FindPos = title.Find( wxT( "_-_" ) );
if( FindPos != wxNOT_FOUND )
{
trackname = title.Mid( 0, FindPos );
}
else
{
trackname = title;
}
}
else
{
trackname = title;
}
}
}
//// -------------------------------------------------------------------------------- //
//void guPlayerPanel::SendRecordSplitEvent( void )
//{
// guLogMessage( wxT( "guPlayerPanel::SendRecordSplitEvent" ) );
// // If its buffering
// if( m_BufferGaugeId != wxNOT_FOUND )
// {
// m_PendingNewRecordName = true;
// //guLogDebug( wxT( "Player is buffering. Will rename recording once its finished" ) );
// return;
// }
// m_MediaRecordCtrl->SplitTrack();
//}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaTags( guMediaEvent &event )
{
//guLogDebug( wxT( "OnMediaTags..." ) );
guRadioTagInfo * RadioTag = ( guRadioTagInfo * ) event.GetClientData();
if( RadioTag )
{
if( ( m_MediaSong.m_Type == guTRACK_TYPE_RADIOSTATION ) ||
( m_NextTrackId && ( m_NextSong.m_Type == guTRACK_TYPE_RADIOSTATION ) ) )
{
//guLogDebug( wxT( "Radio Name: %s" ), wxString( RadioTag->m_Organization, wxConvUTF8 ).c_str() );
if( RadioTag->m_Organization )
{
if( m_NextTrackId )
{
m_NextSong.m_AlbumName = wxString( RadioTag->m_Organization, wxConvUTF8 );
while( m_NextSong.m_AlbumName.StartsWith( wxT( "." ) ) )
m_NextSong.m_AlbumName = m_NextSong.m_AlbumName.Mid( 1 );
if( m_MediaRecordCtrl && m_MediaRecordCtrl->IsRecording() )
{
m_MediaRecordCtrl->SetStation( m_NextSong.m_AlbumName );
}
}
else
{
m_MediaSong.m_AlbumName = wxString( RadioTag->m_Organization, wxConvUTF8 );
SetAlbumLabel( m_MediaSong.m_AlbumName );
if( m_MediaRecordCtrl && m_MediaRecordCtrl->IsRecording() )
{
m_MediaRecordCtrl->SetStation( m_MediaSong.m_AlbumName );
}
}
}
if( RadioTag->m_Genre )
{
//guLogDebug( wxT( "Radio Genre: %s" ), wxString( RadioTag->m_Genre, wxConvUTF8 ).c_str() );
if( m_NextTrackId )
{
m_NextSong.m_GenreName = wxString( RadioTag->m_Genre, wxConvUTF8 );
if( m_MediaRecordCtrl && m_MediaRecordCtrl->IsRecording() )
{
m_MediaRecordCtrl->SetGenre( m_NextSong.m_GenreName );
}
}
else
{
m_MediaSong.m_GenreName = wxString( RadioTag->m_Genre, wxConvUTF8 );
if( m_MediaRecordCtrl && m_MediaRecordCtrl->IsRecording() )
{
m_MediaRecordCtrl->SetGenre( m_MediaSong.m_GenreName );
}
}
}
//guLogDebug( wxT( "MediaTag:'%s'" ), TagStr->c_str() );
if( RadioTag->m_Title )
{
wxString Title( RadioTag->m_Title, wxConvUTF8 );
//guLogDebug( wxT( "Radio Title: %s" ), Title.c_str() );
if( m_NextTrackId )
{
ExtractMetaData( Title,
m_NextSong.m_ArtistName,
m_NextSong.m_SongName );
}
else
{
if( m_AudioScrobble )
m_AudioScrobble->SendPlayedTrack( m_MediaSong );
ExtractMetaData( Title,
m_MediaSong.m_ArtistName,
m_MediaSong.m_SongName );
SetTitleLabel( m_MediaSong.m_SongName );
SetArtistLabel( m_MediaSong.m_ArtistName );
}
//guLogDebug( wxT( "AlbumName: '%s'" ), m_MediaSong.m_AlbumName.c_str() );
if( m_MediaRecordCtrl && m_MediaRecordCtrl->IsRecording() )
{
if( m_NextTrackId )
m_MediaRecordCtrl->SetTrackName( m_NextSong.m_ArtistName, m_NextSong.m_SongName );
else
m_MediaRecordCtrl->SetTrackName( m_MediaSong.m_ArtistName, m_MediaSong.m_SongName );
//SendRecordSplitEvent();
}
if( m_AudioScrobbleEnabled && m_AudioScrobble && m_AudioScrobble->IsOk() )
{
if( !m_NextTrackId )
{
if( m_AudioScrobble )
m_AudioScrobble->SendNowPlayingTrack( m_MediaSong );
}
}
//guLogDebug( wxT( "Sending LastFMPanel::UpdateTrack event" ) );
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_TRACKCHANGED );
event.SetClientData( new guTrack( m_MediaSong ) );
wxPostEvent( m_MainFrame, event );
wxImage Image( guImage( guIMAGE_INDEX_net_radio ) );
SendNotifyInfo( &Image );
}
GetSizer()->Layout();
}
delete RadioTag;
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaBitrate( guMediaEvent &event )
{
//guLogDebug( wxT( "OnMediaBitrate... (%li) %i" ), event.GetExtraLong(), event.GetInt() );
//
// if( m_NextSong.m_Bitrate != BitRate )
// {
// m_NextSong.m_Bitrate = BitRate;
//
// if( m_NextSong.m_Type == guTRACK_TYPE_DB )
// {
// m_Db->UpdateTrackBitRate( m_NextSong.m_SongId, BitRate );
//
// }
//
// // Update the track in database, playlist, etc
// m_MainFrame->UpdatedTrack( guUPDATED_TRACKS_PLAYER, &m_NextSong );
// }
//SetBitRateLabel( BitRate );
if( event.GetExtraLong() == m_CurTrackId )
{
SetBitRate( event.GetInt() );
}
else
{
int BitRate = ( event.GetInt() / 1000 );
if( event.GetExtraLong() == m_NextTrackId )
{
if( m_NextSong.m_Bitrate != BitRate )
{
m_NextSong.m_Bitrate = BitRate;
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaCodec( guMediaEvent &event )
{
if( event.GetExtraLong() == m_CurTrackId )
{
//SetC( event.GetInt() );
guLogDebug( wxT( "OnMedaCodec Cur: %li %s" ), event.GetExtraLong(), event.GetString().c_str() );
SetCodec( event.GetString() );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaLoaded( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaLoaded Cur: %i %i %li" ), m_PlayListCtrl->GetCurItem(), event.GetInt(), m_NextTrackId );
try {
if( event.GetInt() )
{
//
m_MediaCtrl->Play();
}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
catch(...)
{
OnNextTrackButtonClick( event );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaPlayStarted( void )
{
guLogDebug( wxT( "OnMediaPlayStarted %li %li" ), m_CurTrackId, m_NextTrackId );
SavePlayedTrack();
// Enable or disables the record button. Only enabled for radio stations
m_RecordButton->Enable( ( m_NextSong.m_Type == guTRACK_TYPE_RADIOSTATION ) );
m_RecordButton->SetValue( false );
// Set the Current Song
m_CurTrackId = m_NextTrackId;
m_NextTrackId = 0;
m_MediaSong = m_NextSong;
m_TrackChanged = true;
m_SavedPlayedTrack = false;
m_SilenceDetected = false;
m_AboutToEndDetected = false;
m_LastLength = m_MediaSong.m_Length;
if( !m_LastLength )
m_PlayerPositionSlider->SetValue( 0 );
// Update the Current Playing Song Info
UpdateLabels();
//UpdatePositionLabel( 0 );
// m_PlayListCtrl->SetColumnLabel( 0, _( "Now Playing" ) +
// wxString::Format( wxT( ": %i / %li ( %s )" ),
// m_PlayListCtrl->GetCurItem() + 1,
// m_PlayListCtrl->GetCount(),
// m_PlayListCtrl->GetLengthStr().c_str() ) );
wxCommandEvent TitleEvent( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATETITLE );
wxPostEvent( m_MainFrame, TitleEvent );
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_TRACKCHANGED );
event.SetClientData( new guTrack( m_MediaSong ) );
wxPostEvent( m_MainFrame, event );
// Update the cover
UpdateCover();
// Check if Smart is enabled
if( ( m_PlayMode == guPLAYER_PLAYMODE_SMART ) &&
( ( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION ) || ( m_MediaSong.m_Type != guTRACK_TYPE_PODCAST ) ) &&
( !m_SmartPlayMinTracksToPlay || ( ( m_PlayListCtrl->GetCurItem() + m_SmartPlayMinTracksToPlay ) >= m_PlayListCtrl->GetCount() ) ) )
{
SmartAddTracks( m_MediaSong );
}
// If its a Radio disable PositionSlider
//m_PlayerPositionSlider->SetValue( 0 );
if( m_MediaSong.m_Type == guTRACK_TYPE_RADIOSTATION )
{
m_PlayerPositionSlider->Disable();
}
else if( !m_PlayerPositionSlider->IsEnabled() )
{
m_PlayerPositionSlider->Enable();
}
// Send the CapsChanged Event
//wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_CAPSCHANGED );
event.SetId( ID_PLAYERPANEL_CAPSCHANGED );
wxPostEvent( m_MainFrame, event );
if( m_AudioScrobbleEnabled && m_AudioScrobble && m_AudioScrobble->IsOk() )
{
m_AudioScrobble->SendNowPlayingTrack( m_MediaSong );
//m_PendingScrob = false;
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetCurrentCoverImage( wxImage * coverimage, const guSongCoverType covertype, const wxString &coverpath )
{
if( coverimage && coverimage->IsOk() )
{
m_MediaSong.SetCoverImage( coverimage );
m_MediaSong.m_CoverType = covertype;
m_MediaSong.m_CoverPath = coverpath;
}
else //if( covertype == GU_SONGCOVER_NONE )
{
m_MediaSong.SetCoverImage( new wxImage( guImage( guIMAGE_INDEX_no_cover ) ) );
m_MediaSong.m_CoverType = GU_SONGCOVER_NONE;
m_MediaSong.m_CoverPath = wxEmptyString;
}
UpdateCoverImage();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdateCoverImage( const bool shownotify )
{
m_PlayerCoverBitmap->SetBitmap( wxBitmap( * m_MediaSong.m_CoverImage ) );
m_PlayerCoverBitmap->Refresh();
if( shownotify )
SendNotifyInfo( m_MediaSong.m_CoverImage );
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_COVERUPDATED );
wxPostEvent( m_MainFrame, event );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdateCover( const bool shownotify, const bool deleted )
{
// if( m_UpdateCoverThread )
// {
// m_UpdateCoverThread->Pause();
// m_UpdateCoverThread->Delete();
// }
//guLogMessage( wxT( "UpdateCover: '%s' /// '%s' %i" ), m_MediaSong.m_ArtistName.c_str(), m_MediaSong.m_AlbumName.c_str(), deleted );
guUpdatePlayerCoverThread * UpdateCoverThread = new guUpdatePlayerCoverThread( m_Db, m_MainFrame, this, &m_MediaSong, shownotify, deleted );
if( !UpdateCoverThread )
{
guLogError( wxT( "Could not create the UpdateCover thread." ) );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnCoverUpdated( wxCommandEvent &event )
{
// m_UpdateCoverThread = NULL;
UpdateCoverImage( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SavePlayedTrack( const bool forcesave )
{
if( m_SavedPlayedTrack )
return;
m_SavedPlayedTrack = true;
// If have played 'enough' of the song. At least half or >= 4 min.
bool HeardEnought = m_MediaSong.m_PlayTime >= wxMin( guAS_MIN_PLAYTIME * 1000, m_MediaSong.m_Length / 2 );
// Check if the Current Song have played more than the half or >= 4 min and if so add it to
// The CachedPlayedSong database to be submitted to LastFM AudioScrobbling
if( m_AudioScrobbleEnabled && ( m_MediaSong.m_Type != guTRACK_TYPE_PODCAST ) ) // If its not a podcast
{
guLogDebug( wxT( "PlayTime: %u Length: %u" ), m_MediaSong.m_PlayTime, m_MediaSong.m_Length );
if( HeardEnought && // >= 4min || >= half-of-length
( m_MediaSong.m_PlayTime > ( guAS_MIN_TRACKLEN * 1000 ) ) ) // If the Length is more than 30 secs
{
if( !m_MediaSong.m_SongName.IsEmpty() && // Check if we have no missing data
!m_MediaSong.m_ArtistName.IsEmpty() )
{
//
m_AudioScrobble->SendPlayedTrack( m_MediaSong );
}
}
}
// Update the play count if it has played enough of the track
if( m_MediaSong.m_Loaded )
{
if( !SupportedPlayCountTypes.Count() )
{
SupportedPlayCountTypes.Add( guTRACK_TYPE_DB );
SupportedPlayCountTypes.Add( guTRACK_TYPE_IPOD );
SupportedPlayCountTypes.Add( guTRACK_TYPE_JAMENDO );
SupportedPlayCountTypes.Add( guTRACK_TYPE_MAGNATUNE );
SupportedPlayCountTypes.Add( guTRACK_TYPE_PODCAST );
}
if( SupportedPlayCountTypes.Index( m_MediaSong.m_Type ) != wxNOT_FOUND )
{
if( HeardEnought )
{
m_MediaSong.m_PlayCount++;
m_MediaSong.m_LastPlay = wxDateTime::GetTimeNow();
guLogDebug( wxT( "Increased PlayCount to %i" ), m_MediaSong.m_PlayCount );
if( !m_MediaSong.m_Offset && m_MediaSong.m_MediaViewer && m_MediaSong.m_MediaViewer->GetEmbeddMetadata() )
{
guTrackArray Tracks;
Tracks.Add( m_MediaSong );
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
ChangedFlags.Add( guTRACK_CHANGED_DATA_RATING );
guUpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
}
if( m_MediaSong.m_Type != guTRACK_TYPE_PODCAST )
{
if( m_MediaSong.m_MediaViewer )
{
guDbLibrary * Db = m_MediaSong.m_MediaViewer->GetDb();
Db->SetTrackPlayCount( m_MediaSong.m_SongId, m_MediaSong.m_PlayCount );
}
}
else
{
guDbPodcasts * DbPodcasts = m_MainFrame->GetPodcastsDb();
DbPodcasts->SetPodcastItemPlayCount( m_MediaSong.m_SongId, m_MediaSong.m_PlayCount );
}
// Update the track in database, playlist, etc
m_MainFrame->UpdatedTrack( guUPDATED_TRACKS_PLAYER, &m_MediaSong );
}
}
}
m_MainFrame->CheckPendingUpdates( &m_MediaSong, forcesave );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaFinished( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaFinished (%li) Cur: %i %li" ), event.GetExtraLong(), m_PlayListCtrl->GetCurItem(), m_NextTrackId );
if( m_SilenceDetected || m_AboutToEndDetected || m_NextTrackId || ( m_CurTrackId != event.GetExtraLong() ) )
{
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
guLogDebug( wxT( "Media Finished Cancelled... %li %li" ), m_CurTrackId, m_NextTrackId );
return;
}
guTrack * NextItem = m_PlayListCtrl->GetNext( m_PlayMode );
if( NextItem )
{
//m_MediaSong = * NextItem;
SetNextTrack( NextItem );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
else
{
// If the option to play a random track is set
if( m_PlayRandom )
{
// If Repeat was enabled disable it
if( GetPlayLoop() )
SetPlayMode( guPLAYER_PLAYMODE_NONE );
//guLogDebug( wxT( "Getting Random Tracks..." ) );
guTrackArray Tracks;
if( m_Db->GetRandomTracks( &Tracks, m_SmartPlayAddTracks, m_PlayRandomMode,
m_PlayerFilters->GetAllowFilterId(),
m_PlayerFilters->GetDenyFilterId() ) )
{
if( Tracks.Count() )
{
AddToPlayList( Tracks, false );
OnMediaFinished( event );
return;
}
}
}
ResetVumeterLevel();
SavePlayedTrack();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaFadeOutFinished( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaFadeOutFinished (%li) Cur: %i %li" ), event.GetExtraLong(), m_PlayListCtrl->GetCurItem(), m_NextTrackId );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnMediaFadeInStarted( guMediaEvent &event )
{
guLogDebug( wxT( "OnMediaFadeInStarted Cur: %i %li" ), m_PlayListCtrl->GetCurItem(), m_NextTrackId );
}
// -------------------------------------------------------------------------------- //
const guMediaState guPlayerPanel::GetState( void )
{
return m_MediaCtrl->GetState();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::CheckFiltersEnable( void )
{
bool IsEnabled = ( m_PlayMode == guPLAYER_PLAYMODE_SMART ) ||
( ( m_PlayMode == guPLAYER_PLAYMODE_NONE ) && m_PlayRandom );
m_PlayerFilters->EnableFilters( IsEnabled );
}
// -------------------------------------------------------------------------------- //
bool guPlayerPanel::GetPlaySmart()
{
return ( m_PlayMode == guPLAYER_PLAYMODE_SMART );
}
// -------------------------------------------------------------------------------- //
int guPlayerPanel::GetPlayMode()
{
return m_PlayMode;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetPlayMode( int playmode )
{
if( m_PlayMode != playmode )
{
m_PlayMode = playmode;
PlayModeChanged();
}
}
// -------------------------------------------------------------------------------- //
bool guPlayerPanel::GetPlayLoop()
{
return ( m_PlayMode >= guPLAYER_PLAYMODE_REPEAT_PLAYLIST );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPrevTrackButtonClick( wxCommandEvent& event )
{
bool ForceSkip = ( event.GetId() == ID_PLAYERPANEL_PREVTRACK ) ||
( event.GetEventObject() == m_PrevTrackButton );
if( wxGetKeyState( WXK_SHIFT ) && m_MainFrame->IsActive() && ForceSkip )
{
OnPrevAlbumButtonClick( event );
return;
}
guMediaState State;
// wxFileOffset CurPos;
guTrack * PrevItem;
// If we are already in the first Item start again the song from the begining
State = m_MediaCtrl->GetState();
//CurPos = m_MediaCtrl->Tell();
int CurItem = m_PlayListCtrl->GetCurItem();
if( ( ( CurItem == 0 ) && ( State == guMEDIASTATE_PLAYING ) ) ||
( ( State != guMEDIASTATE_STOPPED ) && ( m_LastCurPos > GUPLAYER_MIN_PREVTRACK_POS ) ) )
{
SetPosition( m_MediaSong.m_Offset );
return;
}
PrevItem = m_PlayListCtrl->GetPrev( m_PlayMode, ForceSkip );
if( PrevItem )
{
SetNextTrack( PrevItem );
if( State == guMEDIASTATE_PLAYING )
{
// if( State == guMEDIASTATE_PLAYING )
// {
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE :
( ForceSkip ? guFADERPLAYBIN_PLAYTYPE_REPLACE : guFADERPLAYBIN_PLAYTYPE_AFTER_EOS ), ForceSkip );
// }
}
else
{
if( State == guMEDIASTATE_PAUSED )
{
m_MediaCtrl->Stop();
}
if( m_MediaSong.m_Loaded )
{
SavePlayedTrack();
guCurrentTrack CurrentTrack;
CurrentTrack.m_Rating = 0;
CurrentTrack.m_Year = 0;
m_MediaSong = CurrentTrack;
m_LastCurPos = 0;
m_LastLength = 0;
UpdateLabels();
UpdatePositionLabel( 0 );
m_MediaSong.m_CoverType = GU_SONGCOVER_NONE;
m_MediaSong.m_CoverPath = wxEmptyString;
wxImage * CoverImage = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
// Cover
if( CoverImage )
{
if( CoverImage->IsOk() )
{
m_PlayerCoverBitmap->SetBitmap( wxBitmap( *CoverImage ) );
m_PlayerCoverBitmap->Refresh();
}
delete CoverImage;
}
}
//guLogDebug( wxT( "Prev Track when not playing.." ) );
// m_MediaCtrl->SetCurrentState( GST_STATE_READY );
}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
// //event.Skip();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnNextTrackButtonClick( wxCommandEvent& event )
{
bool ForceSkip = ( event.GetId() == ID_PLAYERPANEL_NEXTTRACK ) ||
( event.GetEventObject() == m_NextTrackButton );
if( wxGetKeyState( WXK_SHIFT ) && m_MainFrame->IsActive() && ForceSkip )
{
OnNextAlbumButtonClick( event );
return;
}
guLogDebug( wxT( "OnNextTrackButtonClick Cur: %i %li %i" ), m_PlayListCtrl->GetCurItem(), m_NextTrackId, event.GetInt() );
guMediaState State;
guTrack * NextItem;
NextItem = m_PlayListCtrl->GetNext( m_PlayMode, ForceSkip );
if( NextItem )
{
State = m_MediaCtrl->GetState();
guLogDebug( wxT( "OnNextTrackButtonClick : State = %i" ), State );
SetNextTrack( NextItem );
if( State == guMEDIASTATE_PLAYING || State == guMEDIASTATE_ERROR )
{
if( ( State != guMEDIASTATE_ERROR ) &&
!ForceSkip &&
!( !m_ForceGapless && m_FadeOutTime ) &&
m_MediaSong.m_Offset && m_NextSong.m_Offset &&
( m_MediaSong.m_FileName == m_NextSong.m_FileName ) &&
( m_MediaSong.m_Number + 1 == m_NextSong.m_Number ) )
{
guLogDebug( wxT( "Simulate track change for track %i => %i" ), m_MediaSong.m_Number, m_NextSong.m_Number );
m_NextTrackId = m_CurTrackId;
OnMediaPlayStarted();
}
else
{
LoadMedia( ( event.GetInt() ? ( guFADERPLAYBIN_PLAYTYPE ) event.GetInt() :
( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE :
( ForceSkip ? guFADERPLAYBIN_PLAYTYPE_REPLACE : guFADERPLAYBIN_PLAYTYPE_AFTER_EOS ) ) ),
ForceSkip );
}
}
else
{
if( State == guMEDIASTATE_PAUSED )
{
m_MediaCtrl->Stop();
}
if( m_MediaSong.m_Loaded )
{
SavePlayedTrack();
guCurrentTrack CurrentTrack;
CurrentTrack.m_Rating = 0;
CurrentTrack.m_Year = 0;
CurrentTrack.m_Length = 0;
m_MediaSong = CurrentTrack;
m_LastCurPos = 0;
m_LastLength = 0;
UpdateLabels();
UpdatePositionLabel( 0 );
m_MediaSong.m_CoverType = GU_SONGCOVER_NONE;
m_MediaSong.m_CoverPath = wxEmptyString;
wxImage * CoverImage = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
// Cover
if( CoverImage )
{
if( CoverImage->IsOk() )
{
m_PlayerCoverBitmap->SetBitmap( wxBitmap( *CoverImage ) );
m_PlayerCoverBitmap->Refresh();
}
delete CoverImage;
}
}
//guLogDebug( wxT( "Next Track when not playing.." ) );
// m_MediaCtrl->SetCurrentState( GST_STATE_READY );
}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
else
{
// If the option to play a random track is set
if( m_PlayRandom )
{
// If Repeat was enabled disable it
if( GetPlayLoop() )
SetPlayMode( guPLAYER_PLAYMODE_NONE );
//guLogDebug( wxT( "Getting Random Tracks..." ) );
guTrackArray Tracks;
if( m_Db->GetRandomTracks( &Tracks, m_SmartPlayAddTracks, m_PlayRandomMode,
m_PlayerFilters->GetAllowFilterId(),
m_PlayerFilters->GetDenyFilterId() ) )
{
AddToPlayList( Tracks, false );
OnNextTrackButtonClick( event );
}
}
else
{
if( m_MediaSong.m_Offset )
{
OnStopButtonClick( event );
}
else
{
SavePlayedTrack();
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnNextAlbumButtonClick( wxCommandEvent& event )
{
guLogDebug( wxT( "OnNextAlbumButtonClick Cur: %i %li" ), m_PlayListCtrl->GetCurItem(), m_NextTrackId );
guMediaState State;
guTrack * NextAlbumTrack = m_PlayListCtrl->GetNextAlbum( m_PlayMode, true );
if( NextAlbumTrack )
{
State = m_MediaCtrl->GetState();
SetNextTrack( NextAlbumTrack );
if( State == guMEDIASTATE_PLAYING )
{
bool ForceSkip = ( event.GetId() == ID_PLAYERPANEL_NEXTTRACK ) ||
( event.GetEventObject() == m_NextTrackButton );
LoadMedia( ( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE ),
ForceSkip );
}
//else
//{
//guLogDebug( wxT( "Next ALbum Track when not playing.." ) );
// m_MediaCtrl->SetCurrentState( GST_STATE_READY );
//}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
else
{
// If the option to play a random track is set
if( m_PlayRandom )
{
// If Repeat was enabled disable it
if( GetPlayLoop() )
SetPlayMode( guPLAYER_PLAYMODE_NONE );
//guLogDebug( wxT( "Getting Random Tracks..." ) );
guTrackArray Tracks;
if( m_Db->GetRandomTracks( &Tracks, m_SmartPlayAddTracks, m_PlayRandomMode,
m_PlayerFilters->GetAllowFilterId(),
m_PlayerFilters->GetDenyFilterId() ) )
{
AddToPlayList( Tracks, false );
OnNextAlbumButtonClick( event );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPrevAlbumButtonClick( wxCommandEvent& event )
{
//guLogDebug( wxT( "OnPrevAlbumButtonClick Cur: %i %li" ), m_PlayListCtrl->GetCurItem(), m_NextTrackId );
guMediaState State;
guTrack * NextAlbumTrack = m_PlayListCtrl->GetPrevAlbum( m_PlayMode, true );
if( NextAlbumTrack )
{
State = m_MediaCtrl->GetState();
SetNextTrack( NextAlbumTrack );
if( State == guMEDIASTATE_PLAYING )
{
bool ForceSkip = ( event.GetId() == ID_PLAYERPANEL_PREVTRACK ) ||
( event.GetEventObject() == m_PrevTrackButton );
LoadMedia( ( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE ),
ForceSkip );
}
//else
//{
//guLogDebug( wxT( "Prev Album Track when not playing.." ) );
// m_MediaCtrl->SetCurrentState( GST_STATE_READY );
//}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayButtonClick( wxCommandEvent& event )
{
guLogDebug( wxT( "OnPlayButtonClick Cur: %i %i %i" ), m_PlayListCtrl->GetCurItem(), m_MediaSong.m_Loaded, m_PlayListCtrl->GetItemCount() );
guMediaState State;
//if( m_PendingNewRecordName )
// m_PendingNewRecordName = false;
// Get The Current Song From m_PlayListCtrl
//guTrack * CurItem = m_PlayListCtrl->GetCurrent();
//if( !m_MediaSong.m_SongId && m_PlayListCtrl->GetItemCount() )
if( !m_MediaSong.m_Loaded && m_PlayListCtrl->GetCount() )
{
if( m_PlayListCtrl->GetCurItem() == wxNOT_FOUND )
m_PlayListCtrl->SetCurrent( 0, m_DelTracksPlayed && !GetPlayLoop() );
//m_MediaSong = * m_PlayListCtrl->GetCurrent();
SetNextTrack( m_PlayListCtrl->GetCurrent() );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
return;
}
if( m_MediaSong.m_Loaded )
{
//State = m_MediaCtrl->GetState();
State = GetState();
guLogDebug( wxT( ">>>> PlayButtonClick State: %i" ), State );
if( State == guMEDIASTATE_PLAYING )
{
if( m_SilenceDetector )
m_SilenceDetected = true;
if( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION )
m_MediaCtrl->Pause();
else
m_MediaCtrl->Stop();
//ResetVumeterLevel();
}
else if( State == guMEDIASTATE_PAUSED )
{
m_MediaCtrl->Play();
}
else if( State == guMEDIASTATE_STOPPED )
{
//guLogDebug( wxT( "Loading '%s'" ), m_NextSong.m_FileName.c_str() );
LoadMedia( ( !m_ForceGapless && m_FadeOutTime ) ? guFADERPLAYBIN_PLAYTYPE_CROSSFADE : guFADERPLAYBIN_PLAYTYPE_REPLACE );
return;
}
m_PlayListCtrl->RefreshAll( m_PlayListCtrl->GetCurItem() );
}
else
{
// If the option to play a random track is set
if( m_PlayRandom )
{
// If Repeat was enabled disable it
if( GetPlayLoop() )
SetPlayMode( guPLAYER_PLAYMODE_NONE );
//guLogDebug( wxT( "Getting Random Tracks..." ) );
guTrackArray Tracks;
if( m_Db->GetRandomTracks( &Tracks, m_SmartPlayAddTracks, m_PlayRandomMode,
m_PlayerFilters->GetAllowFilterId(),
m_PlayerFilters->GetDenyFilterId() ) )
{
AddToPlayList( Tracks, false );
OnPlayButtonClick( event );
}
}
}
//wxLogMessage( wxT( "OnPlayButtonClick Id : %i" ), m_MediaSong.SongId );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnStopButtonClick( wxCommandEvent& event )
{
//guLogDebug( wxT( "OnStopButtonClick Cur: %i" ), m_PlayListCtrl->GetCurItem() );
if( wxGetKeyState( WXK_SHIFT ) )
{
OnStopAtEnd( event );
return;
}
guMediaState State = m_MediaCtrl->GetState();
// guLogDebug( wxT( "State: %i" ), State );
if( State != guMEDIASTATE_STOPPED )
{
m_MediaCtrl->Stop();
//UpdatePositionLabel( 0 );
// if( m_MediaSong.m_Length )
// m_PlayerPositionSlider->SetValue( 0 );
// ResetVumeterLevel();
}
else
{
m_MediaSong = guCurrentTrack();
m_MediaSong.SetCoverImage( new wxImage( guImage( guIMAGE_INDEX_no_cover ) ) );
SetTitleLabel( wxEmptyString );
SetAlbumLabel( wxEmptyString );
SetArtistLabel( wxEmptyString );
SetRatingLabel( 0 );
SetBitRateLabel( 0 );
UpdatePositionLabel(0);
SetCodecLabel( * wxEmptyString, * wxEmptyString);
m_YearLabel->SetLabel( wxEmptyString );
UpdateCover(false, false);
UpdateCoverImage(false);
m_PlayListCtrl->ClearItems();
}
SavePlayedTrack( true );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnStopAtEnd( wxCommandEvent &event )
{
//m_MediaSong.m_Type = guTrackType( int( m_MediaSong.m_Type ) ^ guTRACK_TYPE_STOP_HERE );
m_PlayListCtrl->StopAtEnd();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRecordButtonClick( wxCommandEvent& event )
{
bool IsEnabled = event.IsChecked();
if( IsEnabled )
{
m_MediaRecordCtrl->Start( &m_MediaSong );
}
else
{
m_MediaRecordCtrl->Stop();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRandomPlayButtonClick( wxCommandEvent &event )
{
m_PlayListCtrl->Randomize( ( GetState() == guMEDIASTATE_PLAYING ) );
wxCommandEvent evt( wxEVT_MENU, ID_PLAYERPANEL_TRACKLISTCHANGED );
wxPostEvent( this, evt );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayModeButtonClicked( wxCommandEvent &event )
{
m_PlayMode++;
if( m_PlayMode > guPLAYER_PLAYMODE_REPEAT_TRACK )
m_PlayMode = guPLAYER_PLAYMODE_NONE;
PlayModeChanged();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::PlayModeChanged()
{
CheckFiltersEnable();
UpdatePlayModeButton();
// Send Notification for the mpris interface
wxCommandEvent CmdEvent( wxEVT_MENU, ID_PLAYERPANEL_STATUSCHANGED );
wxPostEvent( m_MainFrame, CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdatePlayModeButton()
{
guIMAGE_INDEX NormalImage;
guIMAGE_INDEX HighlightImage;
wxString Tooltip;
switch( m_PlayMode )
{
case guPLAYER_PLAYMODE_SMART :
NormalImage = guIMAGE_INDEX_player_normal_smart;
HighlightImage = guIMAGE_INDEX_player_highlight_smart;
Tooltip = _( "Smart mode enabled" );
break;
case guPLAYER_PLAYMODE_REPEAT_PLAYLIST :
NormalImage = guIMAGE_INDEX_player_normal_repeat;
HighlightImage = guIMAGE_INDEX_player_highlight_repeat;
Tooltip = _( "Repeat all" );
break;
case guPLAYER_PLAYMODE_REPEAT_TRACK :
NormalImage = guIMAGE_INDEX_player_normal_repeat_single;
HighlightImage = guIMAGE_INDEX_player_highlight_repeat_single;
Tooltip = _( "Repeat one" );
break;
//case guPLAYER_PLAYMODE_NONE :
default :
NormalImage = guIMAGE_INDEX_player_light_smart;
HighlightImage = guIMAGE_INDEX_player_light_smart;
Tooltip = _( "Smart mode disabled" );
break;
}
m_PlayModeButton->SetBitmapLabel( guImage( NormalImage ) );
m_PlayModeButton->SetBitmapHover( guImage( HighlightImage ) );
m_PlayModeButton->SetToolTip( Tooltip );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnLoveBanButtonClick( wxCommandEvent &event )
{
if( m_MediaSong.m_Loaded )
{
if( m_MediaSong.m_ASRating == guAS_RATING_NONE )
m_MediaSong.m_ASRating = guAS_RATING_LOVE;
else if( m_MediaSong.m_ASRating == guAS_RATING_LOVE )
m_MediaSong.m_ASRating = guAS_RATING_BAN;
else
m_MediaSong.m_ASRating = guAS_RATING_NONE;
m_LoveBanButton->SetBitmapLabel( m_MediaSong.m_ASRating < guAS_RATING_BAN ?
guImage( guIMAGE_INDEX_player_normal_love ) :
guImage( guIMAGE_INDEX_player_normal_ban ) );
m_LoveBanButton->SetBitmapDisabled( m_MediaSong.m_ASRating < guAS_RATING_BAN ?
guImage( guIMAGE_INDEX_player_light_love ) :
guImage( guIMAGE_INDEX_player_light_ban ) );
m_LoveBanButton->SetBitmapHover( m_MediaSong.m_ASRating < guAS_RATING_BAN ?
guImage( guIMAGE_INDEX_player_highlight_love ) :
guImage( guIMAGE_INDEX_player_highlight_ban ) );
m_LoveBanButton->SetValue( m_MediaSong.m_ASRating );
}
else
m_LoveBanButton->SetValue( false );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnEqualizerButtonClicked( wxCommandEvent &event )
{
guEq10Band * Eq10Band = new guEq10Band( this, m_MediaCtrl );
if( Eq10Band )
{
if( Eq10Band->ShowModal() == wxID_OK )
{
}
Eq10Band->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnEqualizerRightButtonClicked( wxCommandEvent &event )
{
guLogDebug( "guPlayerPanel::OnEqualizerRightButtonClicked << <%s>", event.GetString() );
m_MediaCtrl->ToggleEqualizer(); // this should return in OnUpdatePipeline
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnUpdatePipeline( wxCommandEvent &event )
{
guLogDebug( "guPlayerPanel::OnUpdatePipeline <<" );
auto wpp = (guFaderPlaybin::WeakPtr *)event.GetClientData();
if( wpp != NULL )
{
if( auto sp = wpp->lock() )
{
(*sp)->RefreshPlaybackItems();
}
else
guLogTrace( "Player update: target fader playbin is gone" );
delete wpp;
}
else
{
guLogTrace( "Player update: target fader playbin is null" );
}
guConfig * Config = ( guConfig * ) guConfig::Get();
if( GetState() == guMEDIASTATE_PLAYING )
{
m_EnableEq = m_MediaCtrl->IsEqualizerEnabled();
m_EnableVolCtls = m_MediaCtrl->IsVolCtlsEnabled();
Config->WriteBool( CONFIG_KEY_GENERAL_EQ_ENABLED, m_EnableEq, CONFIG_PATH_GENERAL );
Config->WriteBool( CONFIG_KEY_GENERAL_VOLUME_ENABLED, m_EnableVolCtls, CONFIG_PATH_GENERAL );
}
else
{
m_EnableVolCtls = Config->ReadBool( CONFIG_KEY_GENERAL_VOLUME_ENABLED, true, CONFIG_PATH_GENERAL );
m_EnableEq = Config->ReadBool( CONFIG_KEY_GENERAL_EQ_ENABLED, true, CONFIG_PATH_GENERAL );
}
m_EqualizerButton->SetBitmapLabel( guImage( m_EnableEq ? guIMAGE_INDEX_player_normal_equalizer : guIMAGE_INDEX_player_light_equalizer ) );
bool fg = m_EnableVolCtls ? Config->ReadBool( CONFIG_KEY_CROSSFADER_FORCE_GAPLESS, false, CONFIG_PATH_CROSSFADER ) : true;
if( fg != m_ForceGapless )
{
event.SetInt( fg );
m_MainFrame->OnSetForceGapless( event );
}
if( m_EnableVolCtls )
{
m_VolumeBar->Show();
m_VolumeButton->Show();
m_ForceGaplessButton->Show();
}
else
{
m_VolumeBar->Hide();
m_VolumeButton->Hide();
m_ForceGaplessButton->Hide();
}
m_RecordButton->SetValue( m_MediaCtrl->IsRecording() );
Layout();
guLogDebug( " guPlayerPanel::OnUpdatePipeline (eq=%i vol=%i fg=%i) >> ", m_EnableEq, m_EnableVolCtls, fg );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnVolCtlToggle( wxCommandEvent &event )
{
guLogDebug( "guPlayerPanel::OnVolCtlToggle << <%s>", event.GetString() );
m_MediaCtrl->ToggleVolCtl();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnLeftClickPlayerCoverBitmap( wxMouseEvent &event )
{
if( m_MediaSong.m_CoverType == GU_SONGCOVER_NONE ||
m_MediaSong.m_CoverType == GU_SONGCOVER_RADIO ||
m_MediaSong.m_CoverType == GU_SONGCOVER_PODCAST )
return;
wxPoint Pos;
Pos = ClientToScreen( m_PlayerCoverBitmap->GetPosition() );
guCoverFrame * BigCover = new guCoverFrame( this, wxID_ANY, wxEmptyString, Pos );
if( BigCover )
{
BigCover->SetBitmap( m_MediaSong.m_CoverType, m_MediaSong.m_CoverPath );
BigCover->Show();
BigCover->SetFocus();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayerPositionSliderBeginSeek( wxScrollEvent &event )
{
m_SliderIsDragged = true;
//
if( m_LastLength )
{
int CurPos = event.GetPosition() * ( m_LastLength / 1000 );
// m_PositionLabel->SetLabel( LenToString( CurPos / 1000 ) + _( " of " ) + LenToString( m_MediaSong.m_Length ) );
// m_PosLabelSizer->Layout();
UpdatePositionLabel( CurPos );
//printf( "Slider Tracking %d\n", CurPos );
//m_MediaCtrl->Seek( CurPos * m_MediaSong.Length );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayerPositionSliderEndSeek( wxScrollEvent &event )
{
// wxFileOffset NewPos;
// if( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION )
// {
// NewPos = event.GetPosition();
// guLogDebug( wxT( "Slider EndSeek Set Pos to %i Of %i" ), ( int ) NewPos, 1000 );
// //printf( "SetPos: %llu\n", ( long long int ) NewPos * m_MediaSong.Length );
// //m_MediaCtrl->Seek( NewPos * m_MediaSong.m_Length );
// SetPosition( NewPos * m_MediaSong.m_Length );
// }
m_SliderIsDragged = false;
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayerPositionSliderChanged( wxScrollEvent &event )
{
wxFileOffset NewPos;
if( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION )
{
NewPos = event.GetPosition();
//guLogDebug( wxT( "Slider Changed Set Pos to %i Of %i" ), ( int ) NewPos, 1000 );
SetPosition( m_MediaSong.m_Offset + ( NewPos * ( m_LastLength / 1000 ) ) );
}
m_SliderIsDragged = false;
// m_MediaCtrl->UnsetCrossfader();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnPlayerPositionSliderMouseWheel( wxMouseEvent &event )
{
if( m_MediaSong.m_Type != guTRACK_TYPE_RADIOSTATION )
{
int Rotation = event.GetWheelRotation() / event.GetWheelDelta();
//guLogDebug( wxT( "Pos : %i -> %i" ), GetPosition(), GetPosition() + ( Rotation * 7000 ) );
SetPosition( m_MediaSong.m_Offset + wxMax( 0, wxMin( ( int ) m_LastLength, GetPosition() + ( Rotation * 7000 ) ) ) );
}
m_SliderIsDragged = false;
// m_MediaCtrl->UnsetCrossfader();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetVolume( double volume )
{
if( volume == m_CurVolume )
return;
if( volume < 0 )
volume = 0;
else if( volume > 100 )
volume = 100;
m_CurVolume = volume;
if( m_VolumeButton != NULL )
{
if( m_CurVolume > 75 )
{
m_VolumeButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_vol_hi ) );
m_VolumeButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_vol_hi ) );
}
else if( m_CurVolume > 50 )
{
m_VolumeButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_vol_mid ) );
m_VolumeButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_vol_mid ) );
}
else if( m_CurVolume == 0 )
{
m_VolumeButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_muted ) );
m_VolumeButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_muted ) );
}
else
{
m_VolumeButton->SetBitmapLabel( guImage( guIMAGE_INDEX_player_normal_vol_low ) );
m_VolumeButton->SetBitmapHover( guImage( guIMAGE_INDEX_player_highlight_vol_low ) );
}
m_VolumeButton->Refresh();
m_VolumeButton->SetToolTip( _( "Volume" ) + wxString::Format( wxT( " %u%%" ), ( int ) volume ) );
}
m_MediaCtrl->SetVolume( volume / ( double ) 100.0 );
if( m_VolumeBar != NULL )
m_VolumeBar->SetValue( m_CurVolume );
wxCommandEvent evt( wxEVT_MENU, ID_PLAYERPANEL_VOLUMECHANGED );
wxPostEvent( m_MainFrame, evt );
}
// -------------------------------------------------------------------------------- //
bool guPlayerPanel::SetPosition( int pos )
{
bool Result = m_MediaCtrl->Seek( pos );
if( Result )
{
wxCommandEvent evt( wxEVT_MENU, ID_PLAYERPANEL_SEEKED );
evt.SetInt( pos );
wxPostEvent( m_MainFrame, evt );
}
return Result;
}
// -------------------------------------------------------------------------------- //
int guPlayerPanel::GetPosition()
{
return m_LastCurPos; //m_MediaCtrl->Tell();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnTitleNameDClicked( wxMouseEvent &event )
{
if( ( m_MediaSong.m_MediaViewer && m_MediaSong.m_SongId ) ||
( m_MediaSong.m_Type == guTRACK_TYPE_PODCAST ) )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_TRACK );
evt.SetInt( m_MediaSong.m_SongId );
evt.SetExtraLong( m_MediaSong.m_Type );
evt.SetClientData( ( void * ) m_MediaSong.m_MediaViewer );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnAlbumNameDClicked( wxMouseEvent &event )
{
if( ( m_MediaSong.m_MediaViewer && m_MediaSong.m_SongId ) ||
( m_MediaSong.m_Type == guTRACK_TYPE_PODCAST ) )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ALBUM );
evt.SetInt( m_MediaSong.m_AlbumId );
evt.SetExtraLong( m_MediaSong.m_Type );
evt.SetClientData( ( void * ) m_MediaSong.m_MediaViewer );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnArtistNameDClicked( wxMouseEvent &event )
{
if( ( m_MediaSong.m_MediaViewer && m_MediaSong.m_SongId ) ||
( m_MediaSong.m_Type == guTRACK_TYPE_PODCAST ) )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ARTIST );
evt.SetInt( m_MediaSong.m_ArtistId );
evt.SetExtraLong( m_MediaSong.m_Type );
evt.SetClientData( ( void * ) m_MediaSong.m_MediaViewer );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnYearDClicked( wxMouseEvent &event )
{
if( m_MediaSong.m_MediaViewer && m_MediaSong.m_Year )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_YEAR );
evt.SetInt( m_MediaSong.m_Year );
evt.SetClientData( ( void * ) m_MediaSong.m_MediaViewer );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRatingChanged( guRatingEvent &event )
{
m_MediaSong.m_Rating = event.GetInt();
//if( m_MediaSong.m_Type == guTRACK_TYPE_DB )
if( m_MediaSong.m_MediaViewer )
{
if( !m_MediaSong.m_Offset && m_MediaSong.m_MediaViewer->GetEmbeddMetadata() )
{
guTrackArray Tracks;
Tracks.Add( m_MediaSong );
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
ChangedFlags.Add( guTRACK_CHANGED_DATA_RATING );
guUpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
}
guDbLibrary * Db = m_MediaSong.m_MediaViewer->GetDb();
Db->SetTrackRating( m_MediaSong.m_SongId, m_MediaSong.m_Rating );
}
else if( ( m_MediaSong.m_Type == guTRACK_TYPE_RADIOSTATION ) ||
( m_MediaSong.m_Type == guTRACK_TYPE_PODCAST ) )
{
m_MediaSong.m_Rating = -1;
m_Rating->SetRating( -1 );
}
// Update the track in database, playlist, etc
m_MainFrame->UpdatedTrack( guUPDATED_TRACKS_PLAYER, &m_MediaSong );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdatedTracks( const guTrackArray * tracks )
{
int count = tracks->Count();
for( int index = 0; index < count; index++ )
{
if( ( tracks->Item( index ).m_FileName == m_MediaSong.m_FileName ) &&
( tracks->Item( index ).m_Offset == m_MediaSong.m_Offset ) )
{
m_MediaSong.Update( tracks->Item( index ) );
// Update the Current Playing Song Info
UpdateLabels();
UpdateCover( false );
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdatedTrack( const guTrack * track )
{
if( track->m_FileName == m_MediaSong.m_FileName )
{
//m_MediaSong = * track;
m_MediaSong.Update( * track );
// Update the Current Playing Song Info
UpdateLabels();
UpdateCover();
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::UpdateLabels( void )
{
guLogDebug( wxT( "UpdateLabels..." ) );
// Update the Current Playing Song Info
SetTitleLabel( m_MediaSong.m_SongName );
SetAlbumLabel( m_MediaSong.m_AlbumName );
SetArtistLabel( m_MediaSong.m_ArtistName );
SetRatingLabel( m_MediaSong.m_Rating );
// m_LoveBanButton->SetValue( m_MediaSong.m_ASRating );
if( m_MediaSong.m_Year > 0 )
{
m_YearLabel->SetLabel( wxString::Format( wxT( "%u" ), m_MediaSong.m_Year ) );
}
else
m_YearLabel->SetLabel( wxEmptyString );
SetBitRateLabel( m_MediaSong.m_Bitrate );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::ResetVumeterLevel( void )
{
guLevelInfo LevelInfo;
LevelInfo.m_Decay_L = -INFINITY;
LevelInfo.m_Decay_R = -INFINITY;
LevelInfo.m_Peak_L = -INFINITY;
LevelInfo.m_Peak_R = -INFINITY;
if( m_PlayerVumeters )
{
m_PlayerVumeters->SetLevels( LevelInfo );
}
}
// -------------------------------------------------------------------------------- //
void Notify_Normalize_String( wxString &text )
{
text.Replace( wxT( "&" ), wxT( "&" ) );
text.Replace( wxT( "<" ), wxT( "<" ) );
text.Replace( wxT( ">" ), wxT( ">" ) );
text.Replace( wxT( "'" ), wxT( "'" ) );
text.Replace( wxT( "\"" ), wxT( """ ) );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SendNotifyInfo( wxImage * image )
{
if( m_ShowNotifications && m_NotifySrv )
{
image->Rescale( 300, 300, wxIMAGE_QUALITY_HIGH );
wxString Body;
if( m_MediaSong.m_Length )
{
Body = LenToString( m_MediaSong.m_Length );
}
if( m_MediaSong.m_Rating > 0 )
{
Body += wxT( " " );
//Body.Append( wxT( "★" ), m_MediaSong.m_Rating );
// There is a wxWidgets bug that dont append the count characters but only one allways
for( int Index = 0; Index < m_MediaSong.m_Rating; Index++ )
{
Body += wxT( "★" );
}
}
Body += wxT( "\n" ) + m_MediaSong.m_ArtistName;
if( !m_MediaSong.m_AlbumName.IsEmpty() )
{
Body += wxT( " / " ) + m_MediaSong.m_AlbumName;
}
Notify_Normalize_String( Body );
m_NotifySrv->Notify( wxEmptyString, m_MediaSong.m_SongName, Body, image );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::SetForceGapless( const bool forcegapless )
{
if( m_ForceGapless != forcegapless )
{
wxCommandEvent event;
OnForceGaplessClick( event );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnVolumeMouseWheel( wxMouseEvent &event )
{
int Rotation = ( event.GetWheelRotation() / event.GetWheelDelta() ) * ( event.ShiftDown() ? 1 : 4 );
//guLogDebug( wxT( "CurVol: %u Rotations:%i" ), m_CurVolume, Rotation );
SetVolume( m_CurVolume + Rotation );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnVolumeChanged( wxScrollEvent &event )
{
SetVolume( event.GetPosition() );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnVolumeClicked( wxCommandEvent &event )
{
if( m_VolumeBar != NULL )
{
if( m_VolumeBar->IsShown() )
m_VolumeBar->Hide();
else
m_VolumeBar->Show();
}
Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnVolumeRightClicked( wxCommandEvent &event )
{
if( m_LastVolume == wxNOT_FOUND )
{
m_LastVolume = m_CurVolume;
SetVolume(0);
}
else
{
SetVolume(m_LastVolume);
m_LastVolume = wxNOT_FOUND;
}
Layout();
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnAddTracks( wxCommandEvent &event )
{
//bool PlayTracks = event.GetInt();
wxArrayString * TrackList = ( wxArrayString * ) event.GetClientData();
if( TrackList )
{
AddToPlayList( * TrackList, true, guINSERT_AFTER_CURRENT_NONE );
delete TrackList;
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRemoveTrack( wxCommandEvent &event )
{
RemoveItem( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRepeat( wxCommandEvent &event )
{
OnPlayModeButtonClicked( event );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnLoop( wxCommandEvent &event )
{
SetPlayMode( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnRandom( wxCommandEvent &event )
{
OnRandomPlayButtonClick( event );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnSetVolume( wxCommandEvent &event )
{
SetVolume( event.GetInt() );
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::OnForceGaplessClick( wxCommandEvent &event )
{
guLogMessage( wxT( "ForceGapless clicked...." ) );
m_ForceGapless = !m_ForceGapless;
m_MediaCtrl->ForceGapless( m_ForceGapless );
if( m_ForceGaplessButton != NULL )
{
m_ForceGaplessButton->SetBitmapLabel( guImage( m_ForceGapless ? guIMAGE_INDEX_player_normal_gapless : guIMAGE_INDEX_player_normal_crossfading ) );
m_ForceGaplessButton->SetBitmapHover( guImage( m_ForceGapless ? guIMAGE_INDEX_player_highlight_gapless : guIMAGE_INDEX_player_highlight_crossfading ) );
m_ForceGaplessButton->SetToolTip( m_ForceGapless ? _( "Enable crossfading" ) : _( "Disable crossfading" ) );
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::MediaViewerClosed( guMediaViewer * mediaviewer )
{
if( m_MediaSong.m_MediaViewer == mediaviewer )
{
m_MediaSong.m_MediaViewer = NULL;
}
if( m_NextSong.m_MediaViewer == mediaviewer )
{
m_NextSong.m_MediaViewer = NULL;
}
}
// -------------------------------------------------------------------------------- //
void guPlayerPanel::CheckStartPlaying( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
guLogDebug( wxT( "CheckStartPlaying: %i" ), m_PlayListCtrl->StartPlaying() );
// There was a track passed as argument that we will play
if( m_PlayListCtrl->StartPlaying() )
{
wxCommandEvent event( wxEVT_MENU, ID_PLAYERPANEL_PLAY );
OnPlayButtonClick( event );
}
else
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_SAVE_CURRENT_TRACK_POSITION, false, CONFIG_PATH_GENERAL ) )
{
m_TrackStartPos = wxMax( 0, Config->ReadNum( CONFIG_KEY_GENERAL_CURRENT_TRACK_POS, 0, CONFIG_PATH_GENERAL ) - 500 );
if( m_TrackStartPos > 0 )
{
wxCommandEvent event;
event.SetInt( Config->ReadNum( CONFIG_KEY_PLAYLIST_CURITEM, 0, CONFIG_PATH_PLAYLIST_NOWPLAYING ) );
OnPlayListDClick( event );
}
else
{
SetNextTrack( m_PlayListCtrl->GetCurrent() );
}
}
else if( m_PlayListCtrl->GetCurItem() != wxNOT_FOUND )
{
SetNextTrack( m_PlayListCtrl->GetCurrent() );
}
}
}
// -------------------------------------------------------------------------------- //
// guUpdatePlayerCoverThread
// -------------------------------------------------------------------------------- //
guUpdatePlayerCoverThread::guUpdatePlayerCoverThread( guDbLibrary * db,
guMainFrame * mainframe, guPlayerPanel * playerpanel, guCurrentTrack * currenttrack,
const bool shownotify, const bool deleted ) : wxThread()
{
m_Db = db;
m_MainFrame = mainframe;
m_PlayerPanel = playerpanel;
m_CurrentTrack = currenttrack;
m_ShowNotify = shownotify;
m_Deleted = deleted;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guUpdatePlayerCoverThread::~guUpdatePlayerCoverThread()
{
}
// -------------------------------------------------------------------------------- //
guUpdatePlayerCoverThread::ExitCode guUpdatePlayerCoverThread::Entry()
{
if( TestDestroy() )
return 0;
wxImage * CoverImage = NULL;
if( m_Deleted )
{
m_CurrentTrack->m_CoverPath = wxEmptyString;
// As it was deleted we dont try to get a new one...
}
else if( m_CurrentTrack->m_Type == guTRACK_TYPE_RADIOSTATION )
{
CoverImage = new wxImage( guImage( guIMAGE_INDEX_net_radio ) );
m_CurrentTrack->m_CoverType = GU_SONGCOVER_RADIO;
}
else if( m_CurrentTrack->m_Type == guTRACK_TYPE_PODCAST )
{
CoverImage = new wxImage( guImage( guIMAGE_INDEX_podcast ) );
m_CurrentTrack->m_CoverType = GU_SONGCOVER_PODCAST;
}
else if( m_CurrentTrack->m_MediaViewer )
{
guMediaViewer * MediaViewer = m_CurrentTrack->m_MediaViewer;
CoverImage = MediaViewer->GetAlbumCover( m_CurrentTrack->m_AlbumId, m_CurrentTrack->m_CoverId,
m_CurrentTrack->m_CoverPath, m_CurrentTrack->m_ArtistName, m_CurrentTrack->m_AlbumName );
m_CurrentTrack->m_CoverType = GU_SONGCOVER_FILE;
}
if( !CoverImage )
{
if( ( CoverImage = guTagGetPicture( m_CurrentTrack->m_FileName ) ) )
{
m_CurrentTrack->m_CoverType = GU_SONGCOVER_ID3TAG;
m_CurrentTrack->m_CoverPath = m_CurrentTrack->m_FileName;
}
else
{
//guLogWarning( wxT( "Trying to find covers in %s" ), wxPathOnly( m_CurrentTrack->m_FileName ).c_str() );
m_CurrentTrack->m_CoverPath = m_PlayerPanel->PlayListCtrl()->FindCoverFile( wxPathOnly( m_CurrentTrack->m_FileName ) );
}
}
if( TestDestroy() )
{
if( CoverImage )
delete CoverImage;
return 0;
}
if( !CoverImage )
{
if( m_CurrentTrack->m_CoverPath.IsEmpty() || !wxFileExists( m_CurrentTrack->m_CoverPath ) )
{
//printf( "No coverpath set\n" );
CoverImage = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
m_CurrentTrack->m_CoverType = GU_SONGCOVER_NONE;
m_CurrentTrack->m_CoverPath = wxEmptyString;
}
else
{
CoverImage = new wxImage( m_CurrentTrack->m_CoverPath );
m_CurrentTrack->m_CoverType = GU_SONGCOVER_FILE;
//m_CurrentTrack->CoverPath = CoverPath;
}
}
if( TestDestroy() )
{
if( CoverImage )
delete CoverImage;
return 0;
}
CoverImage->Rescale( 100, 100, wxIMAGE_QUALITY_HIGH );
//guLogMessage( wxT( " File : %s" ), m_CurrentTrack->m_FileName.c_str() );
//guLogMessage( wxT( " Loaded : %i" ), m_CurrentTrack->m_Loaded );
//guLogMessage( wxT( " Type : %i" ), m_CurrentTrack->m_Type );
//guLogMessage( wxT( " SongId : %i" ), m_CurrentTrack->m_SongId );
//guLogMessage( wxT( "CoverId : %i" ), m_CurrentTrack->m_CoverId );
//guLogMessage( wxT( "Co.Type : %i" ), m_CurrentTrack->m_CoverType );
//guLogMessage( wxT( " Cover : '%s'" ), m_CurrentTrack->m_CoverPath.c_str() );
//guLogMessage( wxT( " Width : %u" ), CoverImage->GetWidth() );
//guLogMessage( wxT( " Height : %u" ), CoverImage->GetHeight() );
//guLogMessage( wxT( "===========================================" ) );
if( ( ( m_CurrentTrack->m_CoverType != GU_SONGCOVER_NONE ) && m_CurrentTrack->m_CoverPath.IsEmpty() ) ||
( m_CurrentTrack->m_CoverType == GU_SONGCOVER_ID3TAG ) )
{
if( CoverImage )
{
wxString LastTmpCoverFile = m_PlayerPanel->LastTmpCoverFile();
if( !LastTmpCoverFile.IsEmpty() )
wxRemoveFile( LastTmpCoverFile );
if( LastTmpCoverFile.EndsWith( wxT( "1.png" ) ) )
LastTmpCoverFile = wxFileName::GetTempDir() + wxT( "/" ) + guTEMPORARY_COVER_FILENAME + wxT( "2.png");
else
LastTmpCoverFile = wxFileName::GetTempDir() + wxT( "/" ) + guTEMPORARY_COVER_FILENAME + wxT( "1.png");
//guLogDebug( wxT( "Saving temp cover file to '%s'" ), LastTmpCoverFile.c_str() );
if( CoverImage->SaveFile( LastTmpCoverFile, wxBITMAP_TYPE_PNG ) )
{
if( m_CurrentTrack->m_CoverPath.IsEmpty() )
m_CurrentTrack->m_CoverPath = LastTmpCoverFile;
m_PlayerPanel->SetLastTmpCoverFile( LastTmpCoverFile );
}
}
}
if( TestDestroy() )
{
if( CoverImage )
delete CoverImage;
return 0;
}
if( m_CurrentTrack->m_CoverImage )
delete m_CurrentTrack->m_CoverImage;
m_CurrentTrack->m_CoverImage = CoverImage;
wxCommandEvent Event( wxEVT_MENU, ID_PLAYERPANEL_COVERUPDATED );
Event.SetInt( m_ShowNotify );
wxPostEvent( m_PlayerPanel, Event );
return 0;
}
}
// -------------------------------------------------------------------------------- //
| 134,916
|
C++
|
.cpp
| 2,992
| 37.573529
| 267
| 0.581821
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,593
|
PlayerFilters.cpp
|
anonbeat_guayadeque/src/ui/player/PlayerFilters.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayerFilters.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guPlayerFilters::guPlayerFilters( wxWindow * parent, guDbLibrary * db ) :
wxPanel( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL )
{
m_Db = db;
wxBoxSizer * FiltersMainSizer;
FiltersMainSizer = new wxBoxSizer( wxVERTICAL );
wxFlexGridSizer* FiltersFlexSizer;
FiltersFlexSizer = new wxFlexGridSizer( 2, 0, 0 );
FiltersFlexSizer->AddGrowableCol( 1 );
FiltersFlexSizer->SetFlexibleDirection( wxBOTH );
FiltersFlexSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticText * FiltersAllowLabel = new wxStaticText( this, wxID_ANY, _( "Allow:" ), wxDefaultPosition, wxDefaultSize, 0 );
FiltersAllowLabel->Wrap( -1 );
FiltersFlexSizer->Add( FiltersAllowLabel, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5 );
wxArrayString m_FilterAllowChoiceChoices;
m_FilterAllowChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterAllowChoiceChoices, 0 );
m_FilterAllowChoice->SetSelection( 0 );
FiltersFlexSizer->Add( m_FilterAllowChoice, 1, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
wxStaticText * FiltersDenyLabel = new wxStaticText( this, wxID_ANY, _( "Deny:" ), wxDefaultPosition, wxDefaultSize, 0 );
FiltersDenyLabel->Wrap( -1 );
FiltersFlexSizer->Add( FiltersDenyLabel, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 );
wxArrayString m_FilterDenyChoiceChoices;
m_FilterDenyChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterDenyChoiceChoices, 0 );
m_FilterDenyChoice->SetSelection( 0 );
FiltersFlexSizer->Add( m_FilterDenyChoice, 1, wxEXPAND|wxRIGHT, 5 );
FiltersMainSizer->Add( FiltersFlexSizer, 1, wxEXPAND, 5 );
SetSizer( FiltersMainSizer );
Layout();
FiltersMainSizer->Fit( this );
UpdateFilters();
guConfig * Config = ( guConfig * ) guConfig::Get();
m_FilterDenyChoice->SetSelection( Config->ReadNum( CONFIG_KEY_PLAYBACK_PLAYLIST_DENY_FILTER, 0, CONFIG_PATH_PLAYBACK ) );
m_FilterAllowChoice->SetSelection( Config->ReadNum( CONFIG_KEY_PLAYBACK_PLAYLIST_ALLOW_FILTER, 0, CONFIG_PATH_PLAYBACK ) );
}
// -------------------------------------------------------------------------------- //
guPlayerFilters::~guPlayerFilters()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteNum( CONFIG_KEY_PLAYBACK_PLAYLIST_ALLOW_FILTER, m_FilterAllowChoice->GetSelection(), CONFIG_PATH_PLAYBACK );
Config->WriteNum( CONFIG_KEY_PLAYBACK_PLAYLIST_DENY_FILTER, m_FilterDenyChoice->GetSelection(), CONFIG_PATH_PLAYBACK );
}
// -------------------------------------------------------------------------------- //
int GetListItemsIdIndex( const guListItems &listitems, const int id )
{
int Count = listitems.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( listitems[ Index ].m_Id == id )
return Index;
}
return 0;
}
// -------------------------------------------------------------------------------- //
void guPlayerFilters::UpdateFilters( void )
{
int CurAllowFilter = wxNOT_FOUND;
int CurDenyFilter = wxNOT_FOUND;
if( m_FilterPlayLists.Count() )
{
CurAllowFilter = m_FilterPlayLists[ m_FilterAllowChoice->GetSelection() ].m_Id;
CurDenyFilter = m_FilterPlayLists[ m_FilterDenyChoice->GetSelection() ].m_Id;
}
m_FilterPlayLists.Empty();
m_FilterPlayLists.Add( new guListItem( wxNOT_FOUND, _( "All" ) ) );
m_Db->GetPlayLists( &m_FilterPlayLists, guPLAYLIST_TYPE_STATIC );
m_Db->GetPlayLists( &m_FilterPlayLists, guPLAYLIST_TYPE_DYNAMIC );
wxArrayString ChoiceItems;
int Count = m_FilterPlayLists.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChoiceItems.Add( m_FilterPlayLists[ Index ].m_Name );
}
m_FilterAllowChoice->Clear();
m_FilterAllowChoice->Append( ChoiceItems );
m_FilterAllowChoice->SetSelection( GetListItemsIdIndex( m_FilterPlayLists, CurAllowFilter ) );
ChoiceItems[ 0 ] = _( "None" );
m_FilterDenyChoice->Clear();
m_FilterDenyChoice->Append( ChoiceItems );
m_FilterDenyChoice->SetSelection( GetListItemsIdIndex( m_FilterPlayLists, CurDenyFilter ) );
}
// -------------------------------------------------------------------------------- //
void guPlayerFilters::EnableFilters( const bool enable )
{
m_FilterAllowChoice->Enable( enable );
m_FilterDenyChoice->Enable( enable );
}
// -------------------------------------------------------------------------------- //
void guPlayerFilters::SetAllowFilterId( const int id )
{
m_FilterAllowChoice->SetSelection( GetListItemsIdIndex( m_FilterPlayLists, id ) );
}
// -------------------------------------------------------------------------------- //
void guPlayerFilters::SetDenyFilterId( const int id )
{
m_FilterDenyChoice->SetSelection( GetListItemsIdIndex( m_FilterPlayLists, id ) );
}
// -------------------------------------------------------------------------------- //
int guPlayerFilters::GetAllowSelection( void )
{
return m_FilterAllowChoice->GetSelection();
}
// -------------------------------------------------------------------------------- //
int guPlayerFilters::GetDenySelection( void )
{
return m_FilterDenyChoice->GetSelection();
}
// -------------------------------------------------------------------------------- //
int guPlayerFilters::GetAllowFilterId( void )
{
int Index = m_FilterAllowChoice->GetSelection();
if( Index != wxNOT_FOUND )
{
return m_FilterPlayLists[ Index ].m_Id;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guPlayerFilters::GetDenyFilterId( void )
{
int Index = m_FilterDenyChoice->GetSelection();
if( Index != wxNOT_FOUND )
{
return m_FilterPlayLists[ Index ].m_Id;
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 7,108
|
C++
|
.cpp
| 155
| 42.8
| 127
| 0.608407
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,594
|
PlayList.cpp
|
anonbeat_guayadeque/src/ui/player/PlayList.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayList.h"
#include "Accelerators.h"
#include "Config.h"
#include "EventCommandIds.h"
#include "dbus/mpris.h"
#include "Images.h"
#include "LabelEditor.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "OnlineLinks.h"
#include "PlayerPanel.h"
#include "PlayListAppend.h"
#include "PlayListFile.h"
#include "Shoutcast.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Utils.h"
#include <wx/types.h>
#include <wx/uri.h>
#include <wx/busyinfo.h>
#define SAVE_PLAYLIST_TIMEOUT 60000
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
//
// -------------------------------------------------------------------------------- //
guPlayerPlayList::guPlayerPlayList( wxWindow * parent, guDbLibrary * db, wxAuiManager * manager ) :
guAuiManagedPanel( parent, manager )
{
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
m_PlayListCtrl = new guPlayList( this, db, NULL, ( guMainFrame * ) parent );
MainSizer->Add( m_PlayListCtrl, 1, wxEXPAND, 5 );
SetSizer( MainSizer );
Layout();
MainSizer->Fit( this );
}
// -------------------------------------------------------------------------------- //
void guPlayerPlayList::SetPlayerPanel( guPlayerPanel * player )
{
m_PlayListCtrl->SetPlayerPanel( player );
}
// -------------------------------------------------------------------------------- //
// guPlayList
// -------------------------------------------------------------------------------- //
guPlayList::guPlayList( wxWindow * parent, guDbLibrary * db, guPlayerPanel * playerpanel, guMainFrame * mainframe ) :
guListView( parent, wxLB_MULTIPLE | guLISTVIEW_ALLOWDRAG |
guLISTVIEW_ALLOWDROP | guLISTVIEW_DRAGSELFITEMS | guLISTVIEW_HIDE_HEADER )
{
wxArrayString Songs;
m_ItemHeight = 40;
InsertColumn( new guListViewColumn( _( "Now Playing" ), 0 ) );
m_Db = db;
m_PlayerPanel = playerpanel;
m_MainFrame = mainframe;
m_TotalLen = 0;
m_CurItem = wxNOT_FOUND;
m_StartPlaying = false;
m_SavePlaylistTimer = NULL;
m_SysFontPointSize = wxSystemSettings::GetFont( wxSYS_SYSTEM_FONT ).GetPointSize();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_MaxPlayedTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_MAX_TRACKS_PLAYED, 15, CONFIG_PATH_PLAYBACK );
m_MinPlayListTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_MIN_TRACKS_PLAY, 4, CONFIG_PATH_PLAYBACK );
m_DelTracksPLayed = Config->ReadNum( CONFIG_KEY_PLAYBACK_DEL_TRACKS_PLAYED, false, CONFIG_PATH_PLAYBACK );
m_PlayBitmap = new wxBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
m_StopBitmap = new wxBitmap( guImage( guIMAGE_INDEX_player_tiny_red_stop ) );
m_NormalStar = new wxBitmap( guImage( guIMAGE_INDEX_star_normal_tiny ) );
m_SelectStar = new wxBitmap( guImage( guIMAGE_INDEX_star_highlight_tiny ) );
Bind( wxEVT_MENU, &guPlayList::OnClearClicked, this, ID_PLAYER_PLAYLIST_CLEAR );
Bind( wxEVT_MENU, &guPlayList::OnRemoveClicked, this, ID_PLAYER_PLAYLIST_REMOVE );
Bind( wxEVT_MENU, &guPlayList::OnSaveClicked, this, ID_PLAYER_PLAYLIST_SAVE );
Bind( wxEVT_MENU, &guPlayList::OnCreateBestOfClicked, this, ID_PLAYER_PLAYLIST_CREATE_BESTOF );
Bind( wxEVT_MENU, &guPlayList::OnEditLabelsClicked, this, ID_PLAYER_PLAYLIST_EDITLABELS );
Bind( wxEVT_MENU, &guPlayList::OnEditTracksClicked, this, ID_PLAYER_PLAYLIST_EDITTRACKS );
Bind( wxEVT_MENU, &guPlayList::OnSearchClicked, this, ID_PLAYER_PLAYLIST_SEARCH );
Bind( wxEVT_MENU, &guPlayList::OnCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guPlayList::OnStopAtEnd, this, ID_PLAYER_PLAYLIST_STOP_ATEND );
Bind( wxEVT_MENU, &guPlayList::SetNextTracks, this, ID_PLAYER_PLAYLIST_SET_NEXT_TRACK );
Bind( wxEVT_MENU, &guPlayList::OnSelectTrack, this, ID_PLAYER_PLAYLIST_SELECT_TITLE );
Bind( wxEVT_MENU, &guPlayList::OnSelectArtist, this, ID_PLAYER_PLAYLIST_SELECT_ARTIST );
Bind( wxEVT_MENU, &guPlayList::OnSelectAlbum, this, ID_PLAYER_PLAYLIST_SELECT_ALBUM );
Bind( wxEVT_MENU, &guPlayList::OnSelectAlbumArtist, this, ID_PLAYER_PLAYLIST_SELECT_ALBUMARTIST );
Bind( wxEVT_MENU, &guPlayList::OnSelectComposer, this, ID_PLAYER_PLAYLIST_SELECT_COMPOSER );
Bind( wxEVT_MENU, &guPlayList::OnSelectYear, this, ID_PLAYER_PLAYLIST_SELECT_YEAR );
Bind( wxEVT_MENU, &guPlayList::OnSelectGenre, this, ID_PLAYER_PLAYLIST_SELECT_GENRE );
Bind( wxEVT_MENU, &guPlayList::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guPlayList::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Bind( guConfigUpdatedEvent, &guPlayList::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guPlayList::OnDeleteFromLibrary, this, ID_PLAYER_PLAYLIST_DELETE_LIBRARY );
Bind( wxEVT_MENU, &guPlayList::OnDeleteFromDrive, this, ID_PLAYER_PLAYLIST_DELETE_DRIVE );
Bind( wxEVT_MENU, &guPlayList::OnSetRating, this, ID_PLAYERPANEL_SETRATING_0, ID_PLAYERPANEL_SETRATING_5 );
Bind( wxEVT_MENU, &guPlayList::OnCreateSmartPlaylist, this, ID_PLAYLIST_SMART_PLAYLIST );
Bind( wxEVT_MENU, &guPlayList::StartSavePlaylistTimer, this, ID_PLAYER_PLAYLIST_START_SAVETIMER );
Bind( wxEVT_TIMER, &guPlayList::OnSavePlaylistTimer, this );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guPlayList::~guPlayList()
{
// Save the guPlayList so it can be reload next time
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
SavePlaylistTracks();
if( m_SavePlaylistTimer )
delete m_SavePlaylistTimer;
if( m_PlayBitmap )
delete m_PlayBitmap;
if( m_StopBitmap )
delete m_StopBitmap;
if( m_NormalStar )
delete m_NormalStar;
if( m_SelectStar )
delete m_SelectStar;
Unbind( wxEVT_MENU, &guPlayList::OnClearClicked, this, ID_PLAYER_PLAYLIST_CLEAR );
Unbind( wxEVT_MENU, &guPlayList::OnRemoveClicked, this, ID_PLAYER_PLAYLIST_REMOVE );
Unbind( wxEVT_MENU, &guPlayList::OnSaveClicked, this, ID_PLAYER_PLAYLIST_SAVE );
Unbind( wxEVT_MENU, &guPlayList::OnCreateBestOfClicked, this, ID_PLAYER_PLAYLIST_CREATE_BESTOF );
Unbind( wxEVT_MENU, &guPlayList::OnEditLabelsClicked, this, ID_PLAYER_PLAYLIST_EDITLABELS );
Unbind( wxEVT_MENU, &guPlayList::OnEditTracksClicked, this, ID_PLAYER_PLAYLIST_EDITTRACKS );
Unbind( wxEVT_MENU, &guPlayList::OnSearchClicked, this, ID_PLAYER_PLAYLIST_SEARCH );
Unbind( wxEVT_MENU, &guPlayList::OnCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guPlayList::OnStopAtEnd, this, ID_PLAYER_PLAYLIST_STOP_ATEND );
Unbind( wxEVT_MENU, &guPlayList::SetNextTracks, this, ID_PLAYER_PLAYLIST_SET_NEXT_TRACK );
Unbind( wxEVT_MENU, &guPlayList::OnSelectTrack, this, ID_PLAYER_PLAYLIST_SELECT_TITLE );
Unbind( wxEVT_MENU, &guPlayList::OnSelectArtist, this, ID_PLAYER_PLAYLIST_SELECT_ARTIST );
Unbind( wxEVT_MENU, &guPlayList::OnSelectAlbum, this, ID_PLAYER_PLAYLIST_SELECT_ALBUM );
Unbind( wxEVT_MENU, &guPlayList::OnSelectAlbumArtist, this, ID_PLAYER_PLAYLIST_SELECT_ALBUMARTIST );
Unbind( wxEVT_MENU, &guPlayList::OnSelectComposer, this, ID_PLAYER_PLAYLIST_SELECT_COMPOSER );
Unbind( wxEVT_MENU, &guPlayList::OnSelectYear, this, ID_PLAYER_PLAYLIST_SELECT_YEAR );
Unbind( wxEVT_MENU, &guPlayList::OnSelectGenre, this, ID_PLAYER_PLAYLIST_SELECT_GENRE );
Unbind( wxEVT_MENU, &guPlayList::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guPlayList::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Unbind( guConfigUpdatedEvent, &guPlayList::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guPlayList::OnDeleteFromLibrary, this, ID_PLAYER_PLAYLIST_DELETE_LIBRARY );
Unbind( wxEVT_MENU, &guPlayList::OnDeleteFromDrive, this, ID_PLAYER_PLAYLIST_DELETE_DRIVE );
Unbind( wxEVT_MENU, &guPlayList::OnSetRating, this, ID_PLAYERPANEL_SETRATING_0, ID_PLAYERPANEL_SETRATING_5 );
Unbind( wxEVT_MENU, &guPlayList::OnCreateSmartPlaylist, this, ID_PLAYLIST_SMART_PLAYLIST );
Unbind( wxEVT_MENU, &guPlayList::StartSavePlaylistTimer, this, ID_PLAYER_PLAYLIST_START_SAVETIMER );
Unbind( wxEVT_TIMER, &guPlayList::OnSavePlaylistTimer, this );
}
// -------------------------------------------------------------------------------- //
void guPlayList::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AccelCmds;
AccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
AccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_0 );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_1 );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_2 );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_3 );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_4 );
AccelCmds.Add( ID_PLAYERPANEL_SETRATING_5 );
if( guAccelDoAcceleratorTable( AccelCmds, AccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_PLAYBACK )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
m_MaxPlayedTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_MAX_TRACKS_PLAYED, 15, CONFIG_PATH_PLAYBACK );
m_MinPlayListTracks = Config->ReadNum( CONFIG_KEY_PLAYBACK_MIN_TRACKS_PLAY, 4, CONFIG_PATH_PLAYBACK );
m_DelTracksPLayed = Config->ReadNum( CONFIG_KEY_PLAYBACK_DEL_TRACKS_PLAYED, false, CONFIG_PATH_PLAYBACK );
}
}
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDropBegin( void )
{
if( GetItemCount() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_GENERAL_DROP_FILES_CLEAR_PLAYLIST, false, CONFIG_PATH_GENERAL ) )
{
ClearItems();
RefreshAll();
m_DragOverItem = wxNOT_FOUND;
//m_CurItem = wxNOT_FOUND;
//guLogMessage( wxT( "ClearPlaylist set on config. Playlist cleared" ) );
}
}
}
// -------------------------------------------------------------------------------- //
bool inline guIsJamendoFile( const wxString &filename )
{
return filename.Find( wxT( "/api.jamendo.com/get2/" ) ) != wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
bool inline guIsMagnatuneFile( const wxString &filename )
{
return filename.Find( wxT( ".magnatune.com/all/" ) ) != wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDropFile( const wxString &filename )
{
guLogMessage( wxT( "Dropping '%s'" ), filename.c_str() );
if( guIsJamendoFile( filename ) || guIsMagnatuneFile( filename ) )
{
AddPlayListItem( wxT( "http:/" ) + filename, guINSERT_AFTER_CURRENT_NONE, wxNOT_FOUND );
}
else if( guIsValidAudioFile( filename ) ||
guPlaylistFile::IsValidPlayList( filename ) ||
guCuePlaylistFile::IsValidFile( filename ) )
{
AddPlayListItem( filename, guINSERT_AFTER_CURRENT_NONE, wxNOT_FOUND );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDropTracks( const guTrackArray * tracks )
{
guLogMessage( wxT( "Dropping tracks" ) );
AddToPlayList( * tracks );
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDropEnd( void )
{
m_DragOverItem = wxNOT_FOUND;
// Once finished send the update guPlayList event to the guPlayList object
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATELIST );
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_GENERAL_DROP_FILES_CLEAR_PLAYLIST, false, CONFIG_PATH_GENERAL ) )
{
event.SetExtraLong( 1 );
}
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
int guPlayList::GetSelectedSongs( guTrackArray * Songs, const bool isdrag ) const
{
wxArrayInt Selection = GetSelectedItems( false );
int Count = Selection.Count();
for( int Index = 0; Index < Count; Index++ )
{
Songs->Add( new guTrack( m_Items[ Selection[ Index ] ] ) );
}
return Count;
}
// -------------------------------------------------------------------------------- //
void guPlayList::RemoveItem( int itemnum )
{
wxMutexLocker Lock( m_ItemsMutex );
int count = m_Items.Count();
if( count && ( itemnum >= 0 ) && ( itemnum < count ) )
{
m_TotalLen -= m_Items[ itemnum ].m_Length;
m_Items.RemoveAt( itemnum );
if( itemnum == m_CurItem )
m_CurItem = wxNOT_FOUND;
else if( itemnum < m_CurItem )
m_CurItem--;
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::RemoveSelected()
{
wxArrayInt Selected = GetSelectedItems( false );
int count = Selected.Count();
for( int index = count - 1; index >= 0; index-- )
{
RemoveItem( Selected[ index ] );
}
ClearSelectedItems();
}
//// -------------------------------------------------------------------------------- //
//static void PrintItems( const guTrackArray &Songs, int IP, int SI, int CI )
//{
// int Count = Songs.Count();
// printf( "SI: %d IP: %d CI: %d\n", SI, IP, CI );
// for( int Index = 0; Index < Count; Index++ )
// {
// printf( "%02d ", Songs[ Index ].m_Number );
// }
// printf( "\n" );
//}
// -------------------------------------------------------------------------------- //
void guPlayList::MoveSelection( void )
{
//guLogMessage( wxT( "MoveSelection %i" ), m_DragOverItem );
//
// Move the Selected Items to the DragOverItem and DragOverFirst
//
int InsertPos;
bool CurItemSet = false;
guTrackArray MoveItems;
wxArrayInt Selection = GetSelectedItems( false );
if( m_DragOverItem == wxNOT_FOUND )
{
m_DragOverItem = m_Items.Count() - 1;
m_DragOverAfter = true;
}
if( !Selection.Count() )
{
return;
}
m_ItemsMutex.Lock();
// Where is the Items to be moved
InsertPos = m_DragOverAfter ? m_DragOverItem + 1 : m_DragOverItem;
// How Many elements to move
int Count = Selection.Count();
//PrintItems( m_Items, InsertPos, Selection[ 0 ], m_CurItem );
// Get a copy of every element to move
for( int Index = 0; Index < Count; Index++ )
{
MoveItems.Add( m_Items[ Selection[ Index ] ] );
}
// Remove the Items and move CurItem and InsertPos
// We move from last (bigger) to first
for( int Index = Count - 1; Index >= 0; Index-- )
{
//guLogMessage( wxT( "%i) ci:%i ip:%i" ), Index, m_CurItem, InsertPos );
m_Items.RemoveAt( Selection[ Index ] );
if( Selection[ Index ] < InsertPos )
InsertPos--;
if( Selection[ Index ] < m_CurItem )
m_CurItem--;
else if( Selection[ Index ] == m_CurItem )
{
m_CurItem = InsertPos + Index;
CurItemSet = true;
}
}
//PrintItems( m_Items, InsertPos, Selection[ 0 ], m_CurItem );
// Insert every element at the InsertPos
for( int Index = 0; Index < Count; Index++ )
{
m_Items.Insert( MoveItems[ Index ], InsertPos );
if( !CurItemSet && ( InsertPos <= m_CurItem ) )
m_CurItem++;
InsertPos++;
}
//PrintItems( m_Items, InsertPos, Selection[ 0 ], m_CurItem );
m_DragOverItem = wxNOT_FOUND;
m_ItemsMutex.Unlock();
ClearSelectedItems();
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnKeyDown( wxKeyEvent &event )
{
if( event.GetKeyCode() == WXK_DELETE )
{
RemoveSelected();
ReloadItems();
wxCommandEvent CmdEvent( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATELIST );
CmdEvent.SetInt( 0 );
CmdEvent.SetExtraLong( 0 );
wxPostEvent( this, CmdEvent );
return;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guPlayList::SetPlayList( const guTrackArray &NewItems )
{
wxMutexLocker Lock( m_ItemsMutex );
m_Items = NewItems;
SetSelection( -1 );
m_CurItem = 0;
m_TotalLen = 0;
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_TotalLen += m_Items[ Index ].m_Length;
}
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guPlayList::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
guTrack Item;
wxRect CutRect;
wxSize TextSize;
wxString TimeStr;
// int OffsetSecLine;
// wxArrayInt Selection;
Item = m_Items[ row ];
m_Attr.m_Font->SetPointSize( m_SysFontPointSize );
m_Attr.m_Font->SetStyle( wxFONTSTYLE_NORMAL );
m_Attr.m_Font->SetWeight( wxFONTWEIGHT_BOLD );
dc.SetFont( * m_Attr.m_Font );
dc.SetBackgroundMode( wxTRANSPARENT );
if( IsSelected( row ) )
{
dc.SetTextForeground( m_Attr.m_SelFgColor );
}
else if( row == m_CurItem )
{
dc.SetTextForeground( m_Attr.m_SelBgColor );
}
else
{
//dc.SetTextForeground( row > m_CurItem ? m_Attr.m_TextFgColor : m_PlayedColor );
dc.SetTextForeground( m_Attr.m_TextFgColor );
}
// Draw the Items Texts
CutRect = rect;
// Draw Play bitmap
if( row == m_CurItem && m_PlayBitmap )
{
dc.DrawBitmap( * m_PlayBitmap, CutRect.x + 2, CutRect.y + 10, true );
CutRect.x += 16;
CutRect.width -= 16;
}
// The DB or NODB Tracks
if( Item.m_Type != guTRACK_TYPE_RADIOSTATION )
{
CutRect.width -= ( 50 + 6 + 2 );
dc.SetClippingRegion( CutRect );
//dc.DrawText( ( Item.m_Number ? wxString::Format( wxT( "%02u - " ), Item.m_Number ) :
// wxT( "" ) ) + Item.m_SongName, CutRect.x + 4, CutRect.y + 4 );
dc.DrawText( Item.m_SongName, CutRect.x + 4, CutRect.y + 2 );
//m_Attr.m_Font->SetPointSize( m_SysFontPointSize - 3 );
//m_Attr.m_Font->SetStyle( wxFONTSTYLE_ITALIC );
m_Attr.m_Font->SetWeight( wxFONTWEIGHT_NORMAL );
dc.SetFont( * m_Attr.m_Font );
dc.DrawText( Item.m_ArtistName + wxT( " - " ) + Item.m_AlbumName, CutRect.x + 4, CutRect.y + m_SecondLineOffset );
dc.DestroyClippingRegion();
// Draw the length and rating
CutRect = rect;
CutRect.x += ( CutRect.width - ( 50 + 6 ) );
CutRect.width = ( 50 + 6 );
dc.SetClippingRegion( CutRect );
//m_Attr.m_Font->SetPointSize( m_SysFontPointSize - 2 );
//m_Attr.m_Font->SetStyle( wxFONTSTYLE_NORMAL );
//dc.SetFont( * m_Attr.m_Font );
int TimeWidth = 56;
if( Item.m_Type & guTRACK_TYPE_STOP_HERE )
{
dc.DrawBitmap( * m_StopBitmap, CutRect.x + 40, CutRect.y + 2, true );
TimeWidth -= 16;
}
TimeStr = LenToString( Item.m_Length );
TextSize = dc.GetTextExtent( TimeStr );
TimeWidth -= TextSize.GetWidth();
if( TimeWidth < 0 )
TimeWidth = 0;
dc.DrawText( TimeStr, CutRect.x + ( TimeWidth / 2 ), CutRect.y + 4 );
//guLogMessage( wxT( "%i - %i" ), TextSize.GetWidth(), TextSize.GetHeight() );
// if( Item.m_Type != guTRACK_TYPE_RADIOSTATION )
// {
// Draw the rating
//OffsetSecLine += 2;
CutRect.x += 1;
CutRect.y += 2;
for( int index = 0; index < 5; index++ )
{
dc.DrawBitmap( ( index >= Item.m_Rating ) ? * m_NormalStar : * m_SelectStar,
CutRect.x + ( 11 * index ), CutRect.y + m_SecondLineOffset + 2, true );
}
// }
}
else
{
dc.DrawText( Item.m_SongName, CutRect.x + 4, CutRect.y + 13 );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnMouse( wxMouseEvent &event )
{
if( event.LeftDown() || event.LeftUp() )
{
int x = event.m_x;
int y = event.m_y;
wxSize Size = m_ListBox->GetClientSize();
if( x >= ( Size.GetWidth() - ( 50 + 6 ) ) )
{
int Item = HitTest( x, y );
//if( Item != wxNOT_FOUND && m_Items[ Item ].m_Type == guTRACK_TYPE_DB )
if( Item != wxNOT_FOUND &&
( m_Items[ Item ].m_Type != guTRACK_TYPE_PODCAST ) &&
( m_Items[ Item ].m_Type != guTRACK_TYPE_RADIOSTATION ) )
{
if( ( size_t ) y > ( ( Item - GetVisibleRowsBegin() ) * m_ItemHeight ) + m_SecondLineOffset + 2 )
{
if( event.LeftDown() )
{
int Rating;
x -= ( Size.GetWidth() - ( 50 + 6 ) );
if( x < 3 )
Rating = 0;
else
Rating = wxMin( 5, ( wxMax( 0, x ) / 11 ) + 1 );
if( m_Items[ Item ].m_Rating == Rating )
{
Rating = 0;
}
m_Items[ Item ].m_Rating = Rating;
RefreshRow( Item );
SetTrackRating( m_Items[ Item ], Rating );
}
return;
}
}
}
}
// Do the inherited procedure
guListView::OnMouse( event );
}
// -------------------------------------------------------------------------------- //
wxCoord guPlayList::OnMeasureItem( size_t n ) const
{
int Height = 4;
// Code taken from the generic/listctrl.cpp file
guPlayList * self = wxConstCast( this, guPlayList );
wxClientDC dc( self );
wxFont Font = GetFont();
Font.SetPointSize( m_SysFontPointSize - 2 );
dc.SetFont( Font );
wxCoord y;
dc.GetTextExtent( wxT( "Hg" ), NULL, &y );
Height += y;
self->m_SecondLineOffset = Height;
// Font.SetPointSize( m_SysFontPointSize - 3 );
// dc.SetFont( Font );
// dc.GetTextExtent( wxT( "Hg" ), NULL, &y );
Height += y + 6;
self->SetItemHeight( Height );
self->m_ItemHeight = Height;
// guLogMessage( wxT( "PlayList::OnMeasureItem %i %i" ), m_SecondLineOffset, Height );
return Height;
}
// -------------------------------------------------------------------------------- //
void guPlayList::DrawBackground( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
wxRect LineRect;
if( row == ( int ) m_DragOverItem )
dc.SetBrush( m_Attr.m_DragBgColor );
//else if( n == ( size_t ) GetSelection() )
else if( IsSelected( row ) )
dc.SetBrush( wxBrush( m_Attr.m_SelBgColor ) );
// else if( n == ( size_t ) m_CurItem )
// dc.SetBrush( wxBrush( m_PlayBgColor ) );
else
dc.SetBrush( wxBrush( row & 1 ? m_Attr.m_OddBgColor : m_Attr.m_EveBgColor ) );
dc.SetPen( * wxTRANSPARENT_PEN );
dc.DrawRectangle( rect );
if( row == ( int ) m_DragOverItem )
{
LineRect = rect;
if( m_DragOverAfter )
LineRect.y += ( LineRect.height - 2 );
LineRect.height = 2;
dc.SetBrush( * wxBLACK_BRUSH );
dc.DrawRectangle( LineRect );
}
}
// -------------------------------------------------------------------------------- //
wxString guPlayList::OnGetItemText( const int row, const int col ) const
{
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guPlayList::GetItemsList( void )
{
}
// -------------------------------------------------------------------------------- //
void guPlayList::ReloadItems( bool reset )
{
SetItemCount( GetCount() );
RefreshAll( m_CurItem );
}
// -------------------------------------------------------------------------------- //
void guPlayList::AddItem( const guTrack &NewItem, const int pos )
{
int InsertPos;
if( m_DragOverItem != wxNOT_FOUND )
{
InsertPos = m_DragOverAfter ? m_DragOverItem + 1 : m_DragOverItem;
if( InsertPos <= m_CurItem )
m_CurItem++;
//guLogMessage( wxT( "Inserted at %i %i" ), m_DragOverItem, m_DragOverAfter );
m_Items.Insert( NewItem, InsertPos );
if( m_DragOverAfter )
m_DragOverItem++;
m_DragOverAfter = true;
}
else
{
InsertPos = pos;
if( InsertPos < 0 || InsertPos > ( int ) m_Items.Count() )
InsertPos = wxNOT_FOUND;
if( InsertPos != wxNOT_FOUND )
{
if( InsertPos <= m_CurItem )
m_CurItem++;
m_Items.Insert( NewItem, InsertPos );
}
else
{
m_Items.Add( NewItem );
}
}
}
//// -------------------------------------------------------------------------------- //
//void guPlayList::AddItem( const guTrack * NewItem )
//{
// AddItem( * NewItem );
//}
//
// -------------------------------------------------------------------------------- //
void guPlayList::SetCurrent( int curitem, bool delold )
{
if( delold && ( curitem != m_CurItem ) && ( m_CurItem != wxNOT_FOUND ) &&
( ( size_t ) m_CurItem < m_Items.Count() ) )
{
m_TotalLen -= m_Items[ m_CurItem ].m_Length;
m_Items.RemoveAt( m_CurItem );
if( m_CurItem < curitem )
curitem--;
ReloadItems();
}
if( curitem >= 0 && curitem <= GetCount() )
m_CurItem = curitem;
else
m_CurItem = wxNOT_FOUND;
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
// -------------------------------------------------------------------------------- //
int guPlayList::GetCurItem( void )
{
return m_CurItem;
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetCurrent( void )
{
// if( ( CurItem == wxNOT_FOUND ) && Items.Count() )
// CurItem = 0;
return GetItem( m_CurItem );
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetNext( const int playmode, const bool forceskip )
{
if( m_Items.Count() )
{
if( m_CurItem == wxNOT_FOUND )
{
m_CurItem = 0;
return &m_Items[ m_CurItem ];
}
else if( !forceskip && ( playmode == guPLAYER_PLAYMODE_REPEAT_TRACK ) )
{
return &m_Items[ m_CurItem ];
}
else if( ( m_CurItem < ( ( int ) m_Items.Count() - 1 ) ) )
{
if( m_DelTracksPLayed && ( playmode <= guPLAYER_PLAYMODE_SMART ) )
{
m_TotalLen -= m_Items[ m_CurItem ].m_Length;
m_Items.RemoveAt( m_CurItem );
ReloadItems();
}
else
m_CurItem++;
return &m_Items[ m_CurItem ];
}
else if( playmode == guPLAYER_PLAYMODE_REPEAT_PLAYLIST )
{
m_CurItem = 0;
return &m_Items[ m_CurItem ];
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetPrev( const int playmode, const bool forceskip )
{
if( m_Items.Count() )
{
if( m_CurItem == wxNOT_FOUND )
{
m_CurItem = 0;
return &m_Items[ m_CurItem ];
}
else if( !forceskip && playmode == guPLAYER_PLAYMODE_REPEAT_TRACK )
{
return &m_Items[ m_CurItem ];
}
else if( m_CurItem > 0 )
{
if( m_DelTracksPLayed && !playmode )
{
m_TotalLen -= m_Items[ m_CurItem ].m_Length;
m_Items.RemoveAt( m_CurItem );
ReloadItems();
}
m_CurItem--;
return &m_Items[ m_CurItem ];
}
else if( playmode == guPLAYER_PLAYMODE_REPEAT_PLAYLIST )
{
m_CurItem = m_Items.Count() - 1;
return &m_Items[ m_CurItem ];
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetNextAlbum( const int playmode, const bool forceskip )
{
int SaveCurItem = m_CurItem;
if( m_Items.Count() )
{
if( m_CurItem == wxNOT_FOUND )
{
m_CurItem = 0;
return &m_Items[ m_CurItem ];
}
// else if( !forceskip && playloop == guPLAYER_PLAYLOOP_TRACK )
// {
// return &m_Items[ m_CurItem ];
// }
else if( ( ( size_t ) m_CurItem < ( m_Items.Count() - 1 ) ) )
{
int CurAlbumId = m_Items[ m_CurItem ].m_AlbumId;
while( ( size_t ) m_CurItem < ( m_Items.Count() - 1 ) )
{
if( m_DelTracksPLayed && !playmode )
{
m_TotalLen -= m_Items[ m_CurItem ].m_Length;
m_Items.RemoveAt( m_CurItem );
ReloadItems();
}
else
m_CurItem++;
if( m_Items[ m_CurItem ].m_AlbumId != CurAlbumId )
break;
}
if( ( size_t ) m_CurItem < ( m_Items.Count() - 1 ) )
return &m_Items[ m_CurItem ];
}
// else if( playloop == guPLAYER_PLAYLOOP_PLAYLIST )
// {
// m_CurItem = 0;
// return &m_Items[ m_CurItem ];
// }
}
m_CurItem = SaveCurItem;
return NULL;
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetPrevAlbum( const int playmode, const bool forceskip )
{
int SaveCurItem = m_CurItem;
if( m_Items.Count() )
{
//guLogMessage( wxT( "GetPrevAlbum... %i" ), m_CurItem );
if( m_CurItem == wxNOT_FOUND )
{
m_CurItem = 0;
return &m_Items[ m_CurItem ];
}
// else if( !forceskip && playloop == guPLAYER_PLAYLOOP_TRACK )
// {
// return &m_Items[ m_CurItem ];
// }
else if( m_CurItem > 0 )
{
int CurAlbumId = m_Items[ m_CurItem ].m_AlbumId;
//guLogMessage( wxT( "CurrentAlbum: %i" ), CurAlbumId );
while( m_CurItem > 0 )
{
if( m_DelTracksPLayed && !playmode )
{
m_TotalLen -= m_Items[ m_CurItem ].m_Length;
m_Items.RemoveAt( m_CurItem );
ReloadItems();
}
m_CurItem--;
//guLogMessage( wxT( "Album %i: %i" ), m_CurItem, m_Items[ m_CurItem ].m_AlbumId );
if( m_Items[ m_CurItem ].m_AlbumId != CurAlbumId )
{
CurAlbumId = m_Items[ m_CurItem ].m_AlbumId;
while( m_CurItem > 0 && m_Items[ m_CurItem ].m_AlbumId == CurAlbumId )
{
//guLogMessage( wxT( "New Album %i: %i" ), m_CurItem, m_Items[ m_CurItem ].m_AlbumId );
m_CurItem--;
}
if( m_Items[ m_CurItem ].m_AlbumId != CurAlbumId )
m_CurItem++;
break;
}
}
if( m_CurItem >= 0 )
return &m_Items[ m_CurItem ];
}
// else if( playloop == guPLAYER_PLAYLOOP_PLAYLIST )
// {
// m_CurItem = m_Items.Count() - 1;
// return &m_Items[ m_CurItem ];
// }
}
m_CurItem = SaveCurItem;
return NULL;
}
// -------------------------------------------------------------------------------- //
guTrack * guPlayList::GetItem( size_t item )
{
size_t ItemsCount = m_Items.Count();
if( ItemsCount && item < ItemsCount )
{
return &m_Items[ item ];
}
return NULL;
}
// -------------------------------------------------------------------------------- //
long guPlayList::GetLength( void ) const
{
return m_TotalLen;
}
// -------------------------------------------------------------------------------- //
wxString guPlayList::GetLengthStr() const
{
return LenToString( m_TotalLen );
}
// -------------------------------------------------------------------------------- //
void guPlayList::ClearItems()
{
for( int Index = m_Items.Count() - 1; Index >= 0; Index-- )
{
m_Items.RemoveAt( Index );
}
m_CurItem = wxNOT_FOUND;
m_TotalLen = 0;
m_PendingLoadIds.Empty();
ClearSelectedItems();
ReloadItems();
//PlayerPanel->UpdateTotalLength();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATELIST );
event.SetInt( 0 );
event.SetExtraLong( 0 );
wxPostEvent( this, event );
event.SetId( ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
// -------------------------------------------------------------------------------- //
void guPlayList::Randomize( const bool isplaying )
{
int pos;
int newpos;
int count = m_Items.Count();
guTrack SavedItem;
if( count > 2 )
{
if( isplaying && m_CurItem > 0 )
{
SavedItem = m_Items[ 0 ];
m_Items[ 0 ] = m_Items[ m_CurItem ];
m_Items[ m_CurItem ] = SavedItem;
m_CurItem = 0;
}
else if( !isplaying )
{
if( m_CurItem != wxNOT_FOUND )
m_CurItem = wxNOT_FOUND;
}
for( int index = 0; index < count; index++ )
{
do {
pos = guRandom( count );
newpos = guRandom( count );
} while( ( pos == newpos ) || ( isplaying && ( m_CurItem == 0 ) && ( !pos || !newpos ) ) );
SavedItem = m_Items[ pos ];
m_Items[ pos ] = m_Items[ newpos ];
m_Items[ newpos ] = SavedItem;
// if( pos == m_CurItem )
// m_CurItem = newpos;
// else if( newpos == m_CurItem )
// m_CurItem = pos;
//wxMilliSleep( 1 );
//guLogMessage( wxT( "%u -> %u" ), pos, newpos );
}
ClearSelectedItems();
Refresh( m_CurItem );
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
}
// -------------------------------------------------------------------------------- //
wxString guPlayList::FindCoverFile( const wxString &dirname )
{
wxDir Dir;
wxString DirName;
wxString FileName;
wxString CurFile;
wxString RetVal = wxEmptyString;
wxArrayString CoverSearchWords;
DirName = dirname;
if( !DirName.EndsWith( wxT( "/" ) ) )
DirName += wxT( '/' );
// Get the SearchCoverWords array
m_MainFrame->GetCollectionsCoverNames( CoverSearchWords );
Dir.Open( DirName );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES ) )
{
do {
CurFile = FileName.Lower();
//guLogMessage( wxT( "Searching %s : %s" ), DirName.c_str(), FileName.c_str() );
if( SearchCoverWords( CurFile, CoverSearchWords ) )
{
if( guIsValidImageFile( CurFile ) )
{
//printf( "Found Cover: " ); printf( CurFile.char_str() ); printf( "\n" );
RetVal = DirName + FileName;
break;
}
}
} while( Dir.GetNext( &FileName ) );
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guPlayList::AddToPlayList( const guTrackArray &items, const bool deleteold, const int aftercurrent )
{
wxMutexLocker Lock( m_ItemsMutex );
int InsertPosition = 0;
switch( aftercurrent )
{
case guINSERT_AFTER_CURRENT_NONE :
InsertPosition = m_Items.Count();
break;
case guINSERT_AFTER_CURRENT_TRACK :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
wxString CurFileName = m_Items[ m_CurItem ].m_FileName;
InsertPosition = m_CurItem + 1;
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_FileName == CurFileName )
{
InsertPosition++;
}
}
break;
}
case guINSERT_AFTER_CURRENT_ALBUM :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
int CurAlbumId = m_Items[ m_CurItem ].m_AlbumId;
InsertPosition = m_CurItem + 1;
if( CurAlbumId )
{
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_AlbumId == CurAlbumId )
{
InsertPosition++;
}
}
}
break;
}
case guINSERT_AFTER_CURRENT_ARTIST :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
int CurArtistId = m_Items[ m_CurItem ].m_ArtistId;
InsertPosition = m_CurItem + 1;
if( CurArtistId )
{
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_ArtistId == CurArtistId )
{
InsertPosition++;
}
}
}
break;
}
}
int Count = items.Count();
for( int Index = 0; Index < Count; Index++ )
{
AddItem( items[ Index ], InsertPosition + Index );
m_TotalLen += items[ Index ].m_Length;
}
while( deleteold && ( m_CurItem != 0 ) && ( ( m_CurItem ) > m_MaxPlayedTracks ) )
{
m_TotalLen -= m_Items[ 0 ].m_Length;
m_Items.RemoveAt( 0 );
m_CurItem--;
}
ReloadItems();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
// -------------------------------------------------------------------------------- //
void guPlayList::AddPlayListItem( const wxString &filename, const int aftercurrent, const int pos )
{
// Check if its a uri or a filename
wxString FileName;
guTrack Track;
guPodcastItem PodcastItem;
wxURI Uri( filename );
int InsertPosition = 0;
switch( aftercurrent )
{
case guINSERT_AFTER_CURRENT_NONE :
InsertPosition = m_Items.Count();
break;
case guINSERT_AFTER_CURRENT_TRACK :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
wxString CurFileName = m_Items[ m_CurItem ].m_FileName;
InsertPosition = m_CurItem + 1;
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_FileName == CurFileName )
{
InsertPosition++;
}
}
break;
}
case guINSERT_AFTER_CURRENT_ALBUM :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
int CurAlbumId = m_Items[ m_CurItem ].m_AlbumId;
InsertPosition = m_CurItem + 1;
if( CurAlbumId )
{
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_AlbumId == CurAlbumId )
{
InsertPosition++;
}
}
}
break;
}
case guINSERT_AFTER_CURRENT_ARTIST :
{
if( m_CurItem != wxNOT_FOUND && m_CurItem < ( int ) m_Items.Count() )
{
int CurArtistId = m_Items[ m_CurItem ].m_ArtistId;
InsertPosition = m_CurItem + 1;
if( CurArtistId )
{
while( ( InsertPosition < ( int ) m_Items.Count() ) &&
m_Items[ InsertPosition ].m_ArtistId == CurArtistId )
{
InsertPosition++;
}
}
}
break;
}
}
//guLogMessage( wxT( "Loading %i %i => %i '%s'" ), aftercurrent, pos, InsertPosition, filename.c_str() );
if( guCuePlaylistFile::IsValidFile( Uri.GetPath() ) ) // If its a cue playlist
{
int InsertPos = wxMax( pos, 0 );
guCuePlaylistFile CuePlaylistFile( filename );
int Count = CuePlaylistFile.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
guCuePlaylistItem &CueItem = CuePlaylistFile.GetItem( Index );
Track.m_SongId = wxNOT_FOUND;
Track.m_SongName = CueItem.m_Name;
Track.m_ArtistName = CueItem.m_ArtistName;
Track.m_Composer = CueItem.m_Composer;
Track.m_Comments = CueItem.m_Comment;
Track.m_AlbumId = 0;
Track.m_AlbumName = CueItem.m_AlbumName;
Track.m_Offset = CueItem.m_Start;
Track.m_Length = CueItem.m_Length;
Track.m_FileName = CueItem.m_TrackPath;
Track.m_Number = Index;
long Year;
if( CueItem.m_Year.ToLong( &Year ) )
Track.m_Year = Year;
Track.m_Rating = wxNOT_FOUND;
AddItem( Track, InsertPosition + InsertPos );
InsertPos++;
}
}
}
else if( guPlaylistFile::IsValidPlayList( Uri.GetPath() ) ) // If its a playlist
{
int InsertPos = wxMax( pos, 0 );
guPlaylistFile PlayList( filename );
int Count = PlayList.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
AddPlayListItem( PlayList.GetItem( Index ).m_Location, aftercurrent, InsertPos++ );
}
}
}
else if( Uri.IsReference() ) // Its a file
{
if( filename.StartsWith( wxT( "file://" ) ) )
{
FileName = wxURI::Unescape( Uri.GetPath() );
}
else
{
FileName = filename;
}
guLogMessage( wxT( "Loading '%s'" ), FileName.c_str() );
if( wxFileExists( FileName ) )
{
if( guIsValidAudioFile( FileName ) )
{
Track.m_FileName = FileName;
if( !m_Db->FindTrackFile( FileName, &Track ) )
{
guDbPodcasts * DbPodcasts = m_MainFrame->GetPodcastsDb();
if( DbPodcasts->GetPodcastItemFile( FileName, &PodcastItem ) )
{
Track.m_Type = guTRACK_TYPE_PODCAST;
Track.m_SongId = PodcastItem.m_Id;
Track.m_SongName = PodcastItem.m_Title;
Track.m_ArtistName = PodcastItem.m_Author;
Track.m_AlbumId = PodcastItem.m_ChId;
Track.m_AlbumName = PodcastItem.m_Channel;
Track.m_Length = PodcastItem.m_Length;
Track.m_PlayCount = PodcastItem.m_PlayCount;
Track.m_Year = 0;
Track.m_Rating = wxNOT_FOUND;
}
else
{
//guLogMessage( wxT( "Reading tags from the file..." ) );
if( Track.ReadFromFile( FileName ) )
{
Track.m_Type = guTRACK_TYPE_NOTDB;
}
else
{
guLogError( wxT( "Could not read tags from file '%s'" ), FileName.c_str() );
}
}
}
m_TotalLen += Track.m_Length;
AddItem( Track, InsertPosition + wxMax( 0, pos ) );
}
else
{
guLogError( wxT( "Could not open the file '%s'" ), filename.c_str() );
}
}
else if( wxDirExists( FileName ) )
{
wxString DirName = FileName;
wxDir Dir;
if( !DirName.EndsWith( wxT( "/" ) ) )
DirName += wxT( "/" );
int InsertPos = pos;
Dir.Open( DirName );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( ( FileName[ 0 ] != '.' ) )
{
AddPlayListItem( DirName + FileName, aftercurrent, InsertPos++ );
}
} while( Dir.GetNext( &FileName ) );
}
}
}
else
{
guLogError( wxT( "File doesnt exist '%s'" ), filename.c_str() );
}
}
else if( guIsJamendoFile( filename ) )
{
//http://api.jamendo.com/get2/stream/track/redirect/?id=594731&streamencoding=ogg2
Track.m_CoverId = 0;
Track.m_SongName = filename;
//Track.m_AlbumName = FileName;
Track.m_Length = 0;
Track.m_Year = 0;
Track.m_Bitrate = 0;
Track.m_Rating = wxNOT_FOUND;
long Id;
FileName = filename;
wxString IdStr = FileName.Mid( FileName.Find( wxT( "/?id=" ) ) + 5 );
IdStr = IdStr.Mid( 0, IdStr.Find( wxT( "&" ) ) );
IdStr.ToLong( &Id );
if( Id )
{
guMediaViewer * JamendoMediaViewer = m_MainFrame->FindCollectionMediaViewer( wxT( "Jamendo" ) );
if( JamendoMediaViewer )
{
guJamendoLibrary * JamendoDb = ( guJamendoLibrary * ) JamendoMediaViewer->GetDb();
if( JamendoDb )
{
JamendoDb->FindTrackId( Id, &Track );
}
}
else if( m_PendingLoadIds.Index( wxT( "Jamendo" ) ) == wxNOT_FOUND )
{
m_PendingLoadIds.Add( wxT( "Jamendo" ) );
}
}
Track.m_Type = guTRACK_TYPE_JAMENDO;
Track.m_FileName = FileName;
AddItem( Track, InsertPosition + wxMax( 0, pos ) );
}
else if( guIsMagnatuneFile( filename ) )
{
FileName = filename;
FileName.Replace( wxT( " " ), wxT( "%20" ) );
wxString SearchStr = FileName;
int FoundPos;
if( ( FoundPos = SearchStr.Find( wxT( "@stream.magnatune" ) ) ) != wxNOT_FOUND )
{
SearchStr = SearchStr.Mid( FoundPos );
SearchStr.Replace( wxT( "@stream." ), wxT( "http://he3." ) );
SearchStr.Replace( wxT( "_nospeech" ), wxEmptyString );
}
else if( ( FoundPos = SearchStr.Find( wxT( "@download.magnatune" ) ) ) != wxNOT_FOUND )
{
SearchStr = SearchStr.Mid( FoundPos );
SearchStr.Replace( wxT( "@download." ), wxT( "http://he3." ) );
SearchStr.Replace( wxT( "_nospeech" ), wxEmptyString );
}
guLogMessage( wxT( "Searching for track '%s'" ), SearchStr.c_str() );
guMediaViewer * MagnatuneMediaViewer = m_MainFrame->FindCollectionMediaViewer( wxT( "Magnatune" ) );
guMagnatuneLibrary * MagnatuneDb = NULL;
if( MagnatuneMediaViewer )
{
MagnatuneDb = ( guMagnatuneLibrary * ) MagnatuneMediaViewer->GetDb();
}
else if( m_PendingLoadIds.Index( wxT( "Magnatune" ) ) == wxNOT_FOUND )
{
m_PendingLoadIds.Add( wxT( "Magnatune" ) );
}
if( !MagnatuneDb || ( MagnatuneDb->GetTrackId( SearchStr, &Track ) == wxNOT_FOUND ) )
{
Track.m_CoverId = 0;
Track.m_SongName = FileName;
//Track.m_AlbumName = FileName;
Track.m_Length = 0;
Track.m_Year = 0;
Track.m_Bitrate = 0;
Track.m_Rating = wxNOT_FOUND;
}
Track.m_Type = guTRACK_TYPE_MAGNATUNE;
Track.m_FileName = FileName;
AddItem( Track, InsertPosition + wxMax( 0, pos ) );
}
else // This should be a radiostation
{
Track.m_Type = guTRACK_TYPE_RADIOSTATION;
Track.m_CoverId = 0;
Track.m_FileName = filename;
Track.m_SongName = filename;
//Track.m_AlbumName = FileName;
Track.m_Length = 0;
Track.m_Year = 0;
Track.m_Bitrate = 0;
Track.m_Rating = wxNOT_FOUND;
AddItem( Track, InsertPosition + wxMax( 0, pos ) );
}
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
// -------------------------------------------------------------------------------- //
void AddPlayListCommands( wxMenu * Menu, int SelCount )
{
if( Menu )
{
wxMenuItem * MenuItem;
wxMenu * SubMenu = new wxMenu();
wxASSERT( SubMenu );
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( ( Commands[ index ].Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND ) ||
( Commands[ index ].Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND ) )
&& ( SelCount != 1 ) )
{
continue;
}
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
SubMenu->Append( MenuItem );
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int TrackCount = m_Items.Count();
if( !TrackCount )
{
MenuItem = new wxMenuItem( Menu, wxNOT_FOUND, _( "Empty Playlist" ), _( "The playlist is empty" ) );
Menu->Append( MenuItem );
return;
}
wxArrayInt SelectedItems = GetSelectedItems( false );
int SelCount = SelectedItems.Count();
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_EDITLABELS,
wxString( _( "Edit Labels" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITLABELS ),
_( "Edit the current selected tracks labels" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the current selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
if( SelCount )
{
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SET_NEXT_TRACK,
_( "Set as Next Track" ),
_( "Move the selected tracks to be played next" ) );
Menu->Append( MenuItem );
wxMenu * RatingMenu = new wxMenu();
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_0, wxT( "☆☆☆☆☆" ), _( "Set the rating to 0" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_1, wxT( "★☆☆☆☆" ), _( "Set the rating to 1" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_2, wxT( "★★☆☆☆" ), _( "Set the rating to 2" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_3, wxT( "★★★☆☆" ), _( "Set the rating to 3" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_4, wxT( "★★★★☆" ), _( "Set the rating to 4" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_PLAYERPANEL_SETRATING_5, wxT( "★★★★★" ), _( "Set the rating to 5" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
Menu->AppendSubMenu( RatingMenu, _( "Rating" ), _( "Set the current selected tracks rating" ) );
Menu->AppendSeparator();
}
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SEARCH,
wxString( _( "Search" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SEARCH ),
_( "Search a track in the playlist by name" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_search ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
// MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_STOP_ATEND,
// wxString( _( "Stop at end" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_STOP_ATEND),
// _( "Stop after current playing or selected track" ) );
// MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_stop ) );
// Menu->Append( MenuItem );
//
// Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SAVE,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu->Append( MenuItem );
if( SelCount == 1 )
{
MenuItem = new wxMenuItem( Menu, ID_PLAYLIST_SMART_PLAYLIST, _( "Create Smart Playlist" ), _( "Create a smart playlist from this track" ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_CREATE_BESTOF, _( "Create Best Of Playlist" ), _( "Create a playlist with the best of this artist" ) );
Menu->Append( MenuItem );
}
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_RANDOMPLAY,
wxString( _( "Randomize Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_RANDOMPLAY ),
_( "Randomize the songs in the playlist" ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_CLEAR,
wxString( _( "Clear Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_CLEAR ),
_( "Remove all tracks from playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_clear ) );
Menu->Append( MenuItem );
if( SelCount )
{
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_REMOVE,
_( "Remove from Playlist" ),
_( "Remove the selected tracks from playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_delete ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_DELETE_LIBRARY,
_( "Remove from Library" ),
_( "Remove the selected tracks from library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_DELETE_DRIVE,
_( "Delete from Drive" ),
_( "Remove the selected tracks from drive" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
if( SelCount == 1 )
{
wxMenu * SubMenu;
SubMenu = new wxMenu();
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_TITLE, _( "Track" ), _( "Selects the current selected track in the library" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_ARTIST, _( "Artist" ), _( "Selects the artist of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_ALBUMARTIST, _( "Album Artist" ), _( "Select the album artist of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_COMPOSER, _( "Composer" ), _( "Select the composer of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_ALBUM, _( "Album" ), _( "Select the album of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_YEAR, _( "Year" ), _( "Select the year of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_SELECT_GENRE, _( "Genre" ), _( "Select the genre of the current song" ) );
SubMenu->Append( MenuItem );
Menu->AppendSubMenu( SubMenu, _( "Select" ), _( "Search in the library" ) );
Menu->AppendSeparator();
}
m_MainFrame->CreateCopyToMenu( Menu );
if( SelCount == 1 && ( m_Items[ SelectedItems[ 0 ] ].m_Type < guTRACK_TYPE_RADIOSTATION ) )
{
AddOnlineLinksMenu( Menu );
}
AddPlayListCommands( Menu, SelCount );
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnClearClicked( wxCommandEvent &event )
{
ClearItems();
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnRemoveClicked( wxCommandEvent &event )
{
RemoveSelected();
ReloadItems();
//PlayerPanel->UpdateTotalLength();
wxCommandEvent CmdEvent( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATELIST );
CmdEvent.SetInt( 0 );
CmdEvent.SetExtraLong( 0 );
wxPostEvent( this, CmdEvent );
CmdEvent.SetId( ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks;
wxArrayInt SelectedItems = GetSelectedItems( false );
int count = SelectedItems.Count();
if( count )
{
Tracks = new guTrackArray();
for( int index = 0; index < count; index++ )
{
Tracks->Add( new guTrack( m_Items[ SelectedItems[ index ] ] ) );
}
}
else
{
Tracks = new guTrackArray( m_Items );
}
int CommandIndex = event.GetId() - ID_COPYTO_BASE;
if( CommandIndex >= guCOPYTO_DEVICE_BASE )
{
CommandIndex -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( CommandIndex );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( m_MainFrame, event );
}
// -------------------------------------------------------------------------------- //
void inline UpdateTracks( const guTrackArray &tracks, const wxArrayInt &changedflags )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( tracks, MediaViewerPtrs );
guTrackArray CurrentTracks;
wxArrayInt CurrentFlags;
int Count = MediaViewerPtrs.Count();
for( int Index = 0; Index < Count; Index++ )
{
CurrentTracks.Empty();
CurrentFlags.Empty();
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ Index ];
GetMediaViewerTracks( tracks, changedflags, MediaViewer, CurrentTracks, CurrentFlags );
if( CurrentTracks.Count() )
{
guDbLibrary * Db = MediaViewer->GetDb();
Db->UpdateSongs( &CurrentTracks, CurrentFlags );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDeleteFromLibrary( wxCommandEvent &event )
{
if( GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to remove the selected tracks from your library?" ),
wxT( "Remove tracks from library" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray SelectedTracks;
wxArrayInt PodcastsIds;
wxArrayInt Selected = GetSelectedItems( false );
int Count = Selected.Count();
for( int Index = Count - 1; Index >= 0; Index-- )
{
const guTrack & Track = m_Items[ Selected[ Index ] ];
if( Track.m_Type == guTRACK_TYPE_PODCAST )
{
PodcastsIds.Add( Track.m_SongId );
}
else if( Track.m_MediaViewer )
{
SelectedTracks.Add( new guTrack( Track ) );
}
if( Selected[ Index ] == m_CurItem )
{
m_CurItem--;
event.SetId( ID_PLAYERPANEL_NEXTTRACK );
wxPostEvent( m_PlayerPanel, event );
}
RemoveItem( Selected[ Index ] );
}
if( SelectedTracks.Count() )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( SelectedTracks, MediaViewerPtrs );
if( ( Count = MediaViewerPtrs.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ Index ];
guTrackArray MediaViewerTracks;
GetMediaViewerTracks( SelectedTracks, MediaViewer, MediaViewerTracks );
guDbLibrary * Db = MediaViewer->GetDb();
Db->DeleteLibraryTracks( &MediaViewerTracks, true );
}
}
}
if( ( Count = PodcastsIds.Count() ) )
{
guPodcastItemArray Podcasts;
guDbPodcasts * DbPodcasts = m_MainFrame->GetPodcastsDb();
DbPodcasts->GetPodcastItems( &Podcasts, PodcastsIds, 0, 0 );
m_MainFrame->RemovePodcastDownloadItems( &Podcasts );
for( int Index = 0; Index < Count; Index++ )
{
DbPodcasts->SetPodcastItemStatus( PodcastsIds[ Index ], guPODCAST_STATUS_DELETED );
}
}
ClearSelectedItems();
ReloadItems();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnDeleteFromDrive( wxCommandEvent &event )
{
if( GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to delete the selected tracks from your drive?\nThis will permanently erase the selected tracks." ),
wxT( "Remove tracks from drive" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray SelectedTracks;
wxArrayInt PodcastsIds;
wxArrayInt Selected = GetSelectedItems( false );
int Count = Selected.Count();
for( int Index = Count - 1; Index >= 0; Index-- )
{
const guTrack & Track = m_Items[ Selected[ Index ] ];
if( Track.m_Type == guTRACK_TYPE_PODCAST )
{
PodcastsIds.Add( Track.m_SongId );
}
else if( Track.m_MediaViewer )
{
SelectedTracks.Add( new guTrack( Track ) );
}
if( Track.m_Type != guTRACK_TYPE_RADIOSTATION &&
Track.m_Type != guTRACK_TYPE_JAMENDO &&
Track.m_Type != guTRACK_TYPE_MAGNATUNE )
{
if( !wxRemoveFile( Track.m_FileName ) )
{
guLogMessage( wxT( "Error deleting '%s'" ), Track.m_FileName.c_str() );
}
}
if( Selected[ Index ] == m_CurItem )
{
m_CurItem--;
event.SetId( ID_PLAYERPANEL_NEXTTRACK );
wxPostEvent( m_PlayerPanel, event );
}
RemoveItem( Selected[ Index ] );
}
if( SelectedTracks.Count() )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( SelectedTracks, MediaViewerPtrs );
if( ( Count = MediaViewerPtrs.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ Index ];
guTrackArray MediaViewerTracks;
GetMediaViewerTracks( SelectedTracks, MediaViewer, MediaViewerTracks );
guDbLibrary * Db = MediaViewer->GetDb();
Db->DeleteLibraryTracks( &MediaViewerTracks, true );
}
}
}
if( ( Count = PodcastsIds.Count() ) )
{
guPodcastItemArray Podcasts;
guDbPodcasts * DbPodcasts = m_MainFrame->GetPodcastsDb();
DbPodcasts->GetPodcastItems( &Podcasts, PodcastsIds, 0, 0 );
m_MainFrame->RemovePodcastDownloadItems( &Podcasts );
for( int Index = 0; Index < Count; Index++ )
{
DbPodcasts->SetPodcastItemStatus( PodcastsIds[ Index ], guPODCAST_STATUS_DELETED );
}
}
ClearSelectedItems();
ReloadItems();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSaveClicked( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
guTrackArray SelectedTracks;
int Count = SelectedItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = m_Items[ SelectedItems[ Index ] ];
if( Track.m_MediaViewer )
SelectedTracks.Add( new guTrack( Track ) );
}
}
else
{
Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = m_Items[ Index ];
if( Track.m_MediaViewer )
SelectedTracks.Add( new guTrack( Track ) );
}
}
if( SelectedTracks.Count() )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( SelectedTracks, MediaViewerPtrs );
if( MediaViewerPtrs.Count() )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ 0 ];
guTrackArray MediaViewerTracks;
GetMediaViewerTracks( SelectedTracks, MediaViewer, MediaViewerTracks );
wxArrayInt TrackIds;
Count = MediaViewerTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
TrackIds.Add( MediaViewerTracks[ Index ].m_SongId );
}
guDbLibrary * Db = MediaViewer->GetDb();
guListItems PlayLists;
Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( m_MainFrame, Db, &TrackIds, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == wxNOT_FOUND )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
Db->CreateStaticPlayList( PLName, TrackIds );
}
else
{
int PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
Db->UpdateStaticPlayList( PLId, TrackIds );
Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
Db->AppendStaticPlayList( PLId, TrackIds );
}
}
MediaViewer->UpdatePlaylists();
}
PlayListAppendDlg->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnCreateBestOfClicked( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( !SelectedItems.IsEmpty() )
{
const guTrack &Track = m_Items[ SelectedItems[ 0 ] ];
if( Track.m_MediaViewer )
{
Track.m_MediaViewer->CreateBestOfPlaylist( Track );
}
else
{
guLogMessage( _( "Can't create a playlist without mediaviewer." ) );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Songs;
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
//
guTrack * Track;
wxArrayInt SelectedItems = GetSelectedItems( false );
int count = SelectedItems.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
Track = &m_Items[ SelectedItems[ index ] ];
if( !Track->m_Offset && ( Track->m_Type < guTRACK_TYPE_RADIOSTATION ) )
{
Songs.Add( new guTrack( * Track ) );
}
}
}
else
{
// If there is no selection then use all songs that are
// recognized in the database.
count = m_Items.Count();
for( int index = 0; index < count; index++ )
{
Track = &m_Items[ index ];
if( !Track->m_Offset && ( Track->m_Type < guTRACK_TYPE_RADIOSTATION ) )
{
Songs.Add( new guTrack( * Track ) );
}
}
}
if( !Songs.Count() )
return;
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Songs, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
guUpdateTracks( Songs, Images, Lyrics, ChangedFlags );
UpdateTracks( Songs, ChangedFlags );
// Update the track in database, playlist, etc
m_MainFrame->UpdatedTracks( guUPDATED_TRACKS_NONE, &Songs );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnEditLabelsClicked( wxCommandEvent &event )
{
guTrackArray SelectedTracks;
//
wxArrayInt SelectedItems = GetSelectedItems( false );
int Count = SelectedItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = m_Items[ SelectedItems[ Index ] ];
if( Track.m_MediaViewer )
{
SelectedTracks.Add( new guTrack( Track ) );
}
}
}
else
{
// If there is no selection then use all songs that are
// recognized in the database.
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = m_Items[ Index ];
if( Track.m_MediaViewer )
{
SelectedTracks.Add( new guTrack( Track ) );
}
}
}
if( SelectedTracks.Count() )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( SelectedTracks, MediaViewerPtrs );
if( MediaViewerPtrs.Count() )
{
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ 0 ];
guTrackArray MediaViewerTracks;
GetMediaViewerTracks( SelectedTracks, MediaViewer, MediaViewerTracks );
guListItems Tracks;
wxArrayInt TrackIds;
int Count = MediaViewerTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = MediaViewerTracks[ Index ];
Tracks.Add( new guListItem( Track.m_SongId, Track.m_SongName ) );
TrackIds.Add( Track.m_SongId );
}
guDbLibrary * Db = MediaViewer->GetDb();
guArrayListItems LabelSets = Db->GetSongsLabels( TrackIds );
guLabelEditor * LabelEditor = new guLabelEditor( this, Db, _( "Tracks Labels Editor" ), false, &Tracks, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the files
Db->UpdateSongsLabels( LabelSets );
}
LabelEditor->Destroy();
wxCommandEvent event( wxEVT_MENU, ID_LABEL_UPDATELABELS );
wxPostEvent( MediaViewer, event );
}
}
}
}
// -------------------------------------------------------------------------------- //
wxString guPlayList::GetItemSearchText( const int row )
{
return m_Items[ row ].m_SongName +
m_Items[ row ].m_ArtistName +
m_Items[ row ].m_AlbumName;
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSearchClicked( wxCommandEvent &event )
{
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Search: " ), _( "Please enter the search term" ), m_LastSearch );
if( EntryDialog->ShowModal() == wxID_OK )
{
m_LastSearch = EntryDialog->GetValue();
wxArrayInt Selection = GetSelectedItems();
long StartItem = 0;
if( Selection.Count() )
StartItem = Selection[ 0 ];
int LastItemFound = FindItem( StartItem, m_LastSearch, true, false );
SetSelection( LastItemFound );
}
EntryDialog->Destroy();
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectTrack( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_TRACK );
evt.SetInt( m_Items[ SelItem ].m_SongId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectArtist( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ARTIST );
evt.SetInt( m_Items[ SelItem ].m_ArtistId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectAlbum( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ALBUM );
evt.SetInt( m_Items[ SelItem ].m_AlbumId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectAlbumArtist( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ALBUMARTIST );
evt.SetInt( m_Items[ SelItem ].m_AlbumArtistId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectComposer( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_COMPOSER );
evt.SetInt( m_Items[ SelItem ].m_ComposerId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectYear( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
int SelYear = m_Items[ SelItem ].m_Year;
if( SelYear )
{
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_YEAR );
evt.SetInt( SelYear );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSelectGenre( wxCommandEvent &event )
{
wxArrayInt SelectedItems = GetSelectedItems( false );
if( SelectedItems.Count() )
{
int SelItem = SelectedItems[ 0 ];
guMediaViewer * MediaViewer = m_Items[ SelItem ].m_MediaViewer;
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_GENRE );
evt.SetInt( m_Items[ SelItem ].m_GenreId );
evt.SetClientData( MediaViewer );
evt.SetExtraLong( m_Items[ SelItem ].m_Type );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
int guPlayList::GetCaps()
{
// NONE = 0x0000
// CAN_GO_NEXT = 0x0001
// CAN_GO_PREV = 0x0002
// *CAN_PAUSE = 0x0004
// *CAN_PLAY = 0x0008
// *CAN_SEEK = 0x0010
// CAN_PROVIDE_METADATA = 0x0020
// CAN_HAS_TRACKLIST = 0x0040
int Caps = MPRIS_CAPS_NONE;
if( m_Items.Count() )
{
if( m_CurItem < ( int ) m_Items.Count() )
Caps |= MPRIS_CAPS_CAN_GO_NEXT;
if( m_CurItem > 0 )
Caps |= MPRIS_CAPS_CAN_GO_PREV;
Caps |= ( MPRIS_CAPS_CAN_PAUSE | MPRIS_CAPS_CAN_PLAY | MPRIS_CAPS_CAN_SEEK | MPRIS_CAPS_CAN_PROVIDE_METADATA );
}
Caps |= MPRIS_CAPS_CAN_HAS_TRACKLIST;
return Caps;
}
// -------------------------------------------------------------------------------- //
void guPlayList::SetNextTracks( wxCommandEvent &event )
{
m_DragOverItem = ( m_CurItem == wxNOT_FOUND ) ? 0 : m_CurItem;
m_DragOverAfter = true;
MoveSelection();
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSearchLinkClicked( wxCommandEvent &event )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
if( Item != wxNOT_FOUND )
{
ExecuteOnlineLink( event.GetId(), GetSearchText( Item ) );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnCommandClicked( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems( false );
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxASSERT( Commands.Count() > 0 );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
const guTrack &Track = m_Items[ Selection[ 0 ] ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
//wxString Path = wxT( "\"" ) + wxPathOnly( m_Items[ Selection[ 0 ] ].m_FileName ) + wxT( "\"" );
wxString Path = wxPathOnly( Track.m_FileName );
Path.Replace( wxT( " " ), wxT( "\\ " ) );
CurCmd.Replace( guCOMMAND_ALBUMPATH, Path );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
int CoverId = Track.m_CoverId;
wxString CoverPath = wxEmptyString;
if( CoverId > 0 && Track.m_MediaViewer )
{
CoverPath = Track.m_MediaViewer->GetDb()->GetCoverPath( CoverId );
}
else
{
CoverPath = FindCoverFile( wxPathOnly( Track.m_FileName ) );
}
if( !CoverPath.IsEmpty() )
{
CurCmd.Replace( guCOMMAND_COVERPATH, wxT( "\"" ) + CoverPath + wxT( "\"" ) );
}
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
wxString SongList = wxEmptyString;
int count = Selection.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + m_Items[ Selection[ index ] ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::UpdatedTracks( const guTrackArray * tracks )
{
// If there are no items in the playlist there is nothing to do
if( !m_Items.Count() )
return;
bool found = false;
int count = tracks->Count();
for( int index = 0; index < count; index++ )
{
int itemcnt = m_Items.Count();
for( int item = 0; item < itemcnt; item++ )
{
if( ( m_Items[ item ].m_FileName == tracks->Item( index ).m_FileName ) &&
( m_Items[ item ].m_Offset == tracks->Item( index ).m_Offset ) )
{
m_Items[ item ] = tracks->Item( index );
found = true;
}
}
}
if( found )
{
RefreshAll();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::UpdatedTrack( const guTrack * track )
{
// If there are no items in the playlist there is nothing to do
if( !m_Items.Count() )
return;
bool found = false;
int item;
int itemcnt = m_Items.Count();
for( item = 0; item < itemcnt; item++ )
{
if( ( m_Items[ item ].m_FileName == track->m_FileName ) &&
( m_Items[ item ].m_Offset == track->m_Offset ) )
{
m_Items[ item ] = * track;
found = true;
}
}
if( found )
{
RefreshAll();
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_START_SAVETIMER );
wxPostEvent( this, event );
}
}
//// -------------------------------------------------------------------------------- //
//wxString inline guPlayList::GetItemName( const int row ) const
//{
// return m_Items[ row ].m_SongName;
//}
//
//// -------------------------------------------------------------------------------- //
//int inline guPlayList::GetItemId( const int row ) const
//{
// return row;
//}
// -------------------------------------------------------------------------------- //
wxString guPlayList::GetSearchText( int item ) const
{
return wxString::Format( wxT( "\"%s\" \"%s\"" ),
m_Items[ item ].m_ArtistName.c_str(),
m_Items[ item ].m_SongName.c_str() );
}
// -------------------------------------------------------------------------------- //
void guPlayList::StopAtEnd( void )
{
int ItemToFlag = wxNOT_FOUND;
wxArrayInt Selection = GetSelectedItems( false );
int Count = Selection.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
if( Selection[ Index ] > ItemToFlag )
ItemToFlag = Selection[ Index ];
}
//if( ( ItemToFlag != wxNOT_FOUND ) && ( ItemToFlag < ( int ) m_Items.Count() ) ) )
// ItemToFlag;
}
else
{
if( ( m_CurItem >= 0 ) && ( m_CurItem < ( int ) m_Items.Count() ) )
ItemToFlag = m_CurItem;
}
if( ( ItemToFlag >= 0 ) && ( ItemToFlag < ( int ) m_Items.Count() ) )
{
m_Items[ ItemToFlag ].m_Type = guTrackType( ( int ) m_Items[ ItemToFlag ].m_Type ^ guTRACK_TYPE_STOP_HERE );
RefreshAll();
if( ItemToFlag == m_CurItem )
{
m_PlayerPanel->StopAtEnd();
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::ClearStopAtEnd( void )
{
if( ( m_CurItem >= 0 ) && ( m_CurItem < ( int ) m_Items.Count() ) )
{
m_Items[ m_CurItem ].m_Type = guTrackType( ( int ) m_Items[ m_CurItem ].m_Type & 0x7FFFFFFF );
RefreshAll();
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSetRating( wxCommandEvent &event )
{
guLogMessage( wxT( "OnSetRating( %i )" ), event.GetId() - ID_PLAYERPANEL_SETRATING_0 );
wxArrayInt Selected = GetSelectedItems( false );
int Count = Selected.Count();
if( Count )
{
int Rating = event.GetId() - ID_PLAYERPANEL_SETRATING_0;
guTrackArray UpdatedTracks;
for( int Index = 0; Index < Count; Index++ )
{
int ItemNum = Selected[ Index ];
m_Items[ ItemNum ].m_Rating = Rating;
RefreshRow( ItemNum );
UpdatedTracks.Add( m_Items[ ItemNum ] );
}
SetTracksRating( UpdatedTracks, Rating );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::SetTrackRating( const guTrack &track, const int rating )
{
guTrackArray Tracks;
Tracks.Add( track );
SetTracksRating( Tracks, rating );
}
// -------------------------------------------------------------------------------- //
void guPlayList::SetTracksRating( const guTrackArray &tracks, const int rating )
{
wxArrayPtrVoid MediaViewerPtrs;
GetMediaViewersList( tracks, MediaViewerPtrs );
guTrackArray CurrentTracks;
wxArrayInt CurrentFlags;
int Count = MediaViewerPtrs.Count();
for( int Index = 0; Index < Count; Index++ )
{
CurrentTracks.Empty();
CurrentFlags.Empty();
guMediaViewer * MediaViewer = ( guMediaViewer * ) MediaViewerPtrs[ Index ];
GetMediaViewerTracks( tracks, guTRACK_CHANGED_DATA_RATING, MediaViewer, CurrentTracks, CurrentFlags );
if( MediaViewer->GetEmbeddMetadata() )
{
guImagePtrArray Images;
wxArrayString Lyrics;
guUpdateTracks( CurrentTracks, Images, Lyrics, CurrentFlags );
}
guDbLibrary * Db = MediaViewer->GetDb();
Db->SetTracksRating( &CurrentTracks, rating );
MediaViewer->UpdatedTracks( guUPDATED_TRACKS_PLAYER_PLAYLIST, &CurrentTracks );
m_PlayerPanel->UpdatedTracks( &CurrentTracks );
}
}
int Index;
int Count;
// -------------------------------------------------------------------------------- //
void guPlayList::MediaViewerCreated( const wxString &uniqueid, guMediaViewer * mediaviewer )
{
if( m_PendingLoadIds.Index( uniqueid ) != wxNOT_FOUND )
{
CheckPendingLoadItems( uniqueid, mediaviewer );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::MediaViewerClosed( guMediaViewer * mediaviewer )
{
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack & Track = m_Items[ Index ];
if( Track.m_MediaViewer == mediaviewer )
{
Track.m_MediaViewer = NULL;
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::CheckPendingLoadItems( const wxString &uniqueid, guMediaViewer * mediaviewer )
{
int Type;
guDbLibrary * Db = NULL;
if( !mediaviewer )
return;
if( uniqueid == wxT( "Jamendo" ) )
{
Type = guTRACK_TYPE_JAMENDO;
}
else if( uniqueid == wxT( "Magnatune" ) )
{
Type = guTRACK_TYPE_MAGNATUNE;
}
else
return;
Db = mediaviewer->GetDb();
if( !Db )
return;
wxString FileName;
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack & Track = m_Items[ Index ];
if( Track.m_Type == Type )
{
//guLogMessage( wxT( "Trying: '%s'" ), Track.m_FileName.c_str() );
if( Type == guTRACK_TYPE_JAMENDO )
{
long Id;
FileName = Track.m_FileName;
wxString IdStr = FileName.Mid( FileName.Find( wxT( "/?id=" ) ) + 5 );
IdStr = IdStr.Mid( 0, IdStr.Find( wxT( "&" ) ) );
IdStr.ToLong( &Id );
if( Id )
{
Db->FindTrackId( Id, &Track );
Track.m_Type = guTRACK_TYPE_JAMENDO;
Track.m_FileName = FileName;
Track.m_MediaViewer = mediaviewer;
}
}
else
{
FileName = Track.m_FileName;
FileName.Replace( wxT( " " ), wxT( "%20" ) );
wxString SearchStr = FileName;
int FoundPos;
if( ( FoundPos = SearchStr.Find( wxT( "@stream.magnatune" ) ) ) != wxNOT_FOUND )
{
SearchStr = SearchStr.Mid( FoundPos );
SearchStr.Replace( wxT( "@stream." ), wxT( "http://he3." ) );
SearchStr.Replace( wxT( "_nospeech" ), wxEmptyString );
}
else if( ( FoundPos = SearchStr.Find( wxT( "@download.magnatune" ) ) ) != wxNOT_FOUND )
{
SearchStr = SearchStr.Mid( FoundPos );
SearchStr.Replace( wxT( "@download." ), wxT( "http://he3." ) );
SearchStr.Replace( wxT( "_nospeech" ), wxEmptyString );
}
guLogMessage( wxT( "Searching for track '%s'" ), SearchStr.c_str() );
( ( guMagnatuneLibrary * ) Db )->GetTrackId( SearchStr, &Track );
Track.m_Type = guTRACK_TYPE_MAGNATUNE;
Track.m_FileName = FileName;
Track.m_MediaViewer = mediaviewer;
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnCreateSmartPlaylist( wxCommandEvent &event )
{
wxArrayInt Selected = GetSelectedItems( false );
if( Selected.Count() )
{
const guTrack &Track = m_Items[ Selected[ 0 ] ];
if( Track.m_MediaViewer )
{
Track.m_MediaViewer->CreateSmartPlaylist( Track.m_ArtistName, Track.m_SongName );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::SavePlaylistTracks( void )
{
guTrackArray Tracks;
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config->ReadBool( CONFIG_KEY_PLAYLIST_SAVE_ON_CLOSE, true, CONFIG_PATH_PLAYLIST ) )
{
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items[ Index ].m_Type < guTRACK_TYPE_IPOD )
Tracks.Add( new guTrack( m_Items[ Index ] ) );
}
Config->SavePlaylistTracks( Tracks, m_CurItem );
}
else
{
Config->SavePlaylistTracks( Tracks, wxNOT_FOUND );
}
}
// -------------------------------------------------------------------------------- //
void guPlayList::LoadPlaylistTracks( void )
{
wxBusyInfo BusyInfo( _( "Loading tracks. Please wait" ) );
wxTheApp->Yield();
guMainApp * MainApp = ( guMainApp * ) wxTheApp;
if( MainApp && MainApp->argc > 1 )
{
int Count = MainApp->argc;
for( int Index = 1; Index < Count; Index++ )
{
//guLogMessage( wxT( "%u-%u %s" ), Index, MainApp->argc, MainApp->argv[ Index ] );
AddPlayListItem( MainApp->argv[ Index ], guINSERT_AFTER_CURRENT_NONE, wxNOT_FOUND );
}
m_CurItem = wxNOT_FOUND;
m_StartPlaying = true;
}
else
{
guTrackArray Tracks;
guConfig * Config = ( guConfig * ) guConfig::Get();
int CurItem = Config->LoadPlaylistTracks( Tracks );
if( ( size_t ) m_CurItem > Tracks.Count() )
m_CurItem = wxNOT_FOUND;
wxTheApp->Yield();
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Tracks[ Index ].m_Offset ||
( Tracks[ Index ].m_Type == guTRACK_TYPE_RADIOSTATION ) )
{
m_Items.Add( new guTrack( Tracks[ Index ] ) );
}
else
{
AddPlayListItem( Tracks[ Index ].m_FileName, guINSERT_AFTER_CURRENT_NONE, wxNOT_FOUND );
}
}
m_CurItem = CurItem;
}
wxCommandEvent event( wxEVT_MENU, ID_PLAYER_PLAYLIST_UPDATELIST );
event.SetInt( 1 );
wxPostEvent( this, event );
}
// -------------------------------------------------------------------------------- //
void guPlayList::StartSavePlaylistTimer( wxCommandEvent &event )
{
if( !m_SavePlaylistTimer )
{
m_SavePlaylistTimer = new wxTimer( this );
}
m_SavePlaylistTimer->Start( SAVE_PLAYLIST_TIMEOUT, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guPlayList::OnSavePlaylistTimer( wxTimerEvent & )
{
SavePlaylistTracks();
}
}
// -------------------------------------------------------------------------------- //
| 99,163
|
C++
|
.cpp
| 2,466
| 31.24412
| 163
| 0.518615
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,595
|
TrackChangeInfo.cpp
|
anonbeat_guayadeque/src/ui/player/TrackChangeInfo.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TrackChangeInfo.h"
#include "MediaViewer.h"
#include <wx/arrimpl.cpp>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
WX_DEFINE_OBJARRAY( guTrackChangeInfoArray )
}
// -------------------------------------------------------------------------------- //
| 1,375
|
C++
|
.cpp
| 29
| 46.206897
| 86
| 0.547015
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,596
|
SplashWin.cpp
|
anonbeat_guayadeque/src/ui/splash/SplashWin.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "SplashWin.h"
#include "EventCommandIds.h"
#include "Images.h"
#include "Settings.h"
#include "Utils.h"
#include "Version.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guSplashFrame::guSplashFrame( wxWindow * parent, int timeout ) :
wxFrame( parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 500,275 ), wxSTAY_ON_TOP | wxNO_BORDER | wxFRAME_TOOL_WINDOW )
{
CentreOnScreen();
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
m_Bitmap = new wxBitmap( guImage( guIMAGE_INDEX_splash ) );
wxBoxSizer* MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
wxColour FontColor = wxColour( 100, 100, 100 );
wxString Version = wxT( ID_GUAYADEQUE_VERSION );
#ifdef ID_GUAYADEQUE_REVISION
Version += wxT( "-" ID_GUAYADEQUE_REVISION );
#endif
m_Version = new wxStaticText( this, wxID_ANY, Version, wxDefaultPosition, wxDefaultSize, 0 );
wxFont CurFont = m_Version->GetFont();
CurFont.SetPointSize( CurFont.GetPointSize() + 2 );
m_Version->SetFont( CurFont );
m_Version->Wrap( -1 );
m_Version->SetForegroundColour( FontColor );
m_Version->SetBackgroundColour( * wxWHITE );
MainSizer->Add( m_Version, 0, wxALIGN_RIGHT|wxTOP|wxRIGHT|wxLEFT, 5 );
MainSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_Email = new wxHyperlinkCtrl( this, wxID_ANY, guSPLASH_NAME wxT( " " ) guSPLASH_EMAIL, wxT( "mailto:" ) guSPLASH_EMAIL, wxDefaultPosition, wxDefaultSize, wxHL_ALIGN_RIGHT );
m_Email->SetHoverColour( FontColor );
m_Email->SetNormalColour( FontColor );
m_Email->SetVisitedColour( FontColor );
m_Email->SetBackgroundColour( * wxWHITE );
m_Email->SetCanFocus( false );
MainSizer->Add( m_Email, 0, wxALIGN_RIGHT|wxRIGHT|wxLEFT, 5 );
m_HomePage = new wxHyperlinkCtrl( this, wxID_ANY, guSPLASH_HOMEPAGE, guSPLASH_HOMEPAGE, wxDefaultPosition, wxDefaultSize, wxHL_ALIGN_RIGHT );
m_HomePage->SetHoverColour( FontColor );
m_HomePage->SetNormalColour( FontColor );
m_HomePage->SetVisitedColour( FontColor );
m_HomePage->SetBackgroundColour( * wxWHITE );
m_HomePage->SetCanFocus( false );
MainSizer->Add( m_HomePage, 0, wxALIGN_RIGHT|wxRIGHT|wxLEFT, 5 );
m_Donate = new wxHyperlinkCtrl( this, wxID_ANY, _( "Please Donate!" ), guSPLASH_DONATION_LINK );
m_Donate->SetHoverColour( FontColor );
m_Donate->SetNormalColour( FontColor );
m_Donate->SetVisitedColour( FontColor );
m_Donate->SetBackgroundColour( * wxWHITE );
m_Donate->SetCanFocus( false );
MainSizer->Add( m_Donate, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
this->SetSizer( MainSizer );
this->Layout();
Show( true );
SetThemeEnabled( false );
SetBackgroundStyle( wxBG_STYLE_ERASE );
m_Timer.SetOwner( this );
m_Timer.Start( timeout, wxTIMER_ONE_SHOT );
// Bind Events
Bind( wxEVT_ERASE_BACKGROUND, &guSplashFrame::OnEraseBackground, this );
Bind( wxEVT_LEFT_DOWN, &guSplashFrame::OnSplashClick, this );
Bind( wxEVT_TIMER, &guSplashFrame::OnTimeout, this );
}
// -------------------------------------------------------------------------------- //
guSplashFrame::~guSplashFrame()
{
if( m_Bitmap )
{
delete m_Bitmap;
}
// Unbind Events
Unbind( wxEVT_ERASE_BACKGROUND, &guSplashFrame::OnEraseBackground, this );
Unbind( wxEVT_LEFT_DOWN, &guSplashFrame::OnSplashClick, this );
Unbind( wxEVT_TIMER, &guSplashFrame::OnTimeout, this );
}
// -------------------------------------------------------------------------------- //
void guSplashFrame::OnSplashClick( wxMouseEvent &event )
{
Close();
}
// -------------------------------------------------------------------------------- //
void guSplashFrame::OnCloseWindow( wxCloseEvent &event )
{
m_Timer.Stop();
this->Destroy();
}
// -------------------------------------------------------------------------------- //
void guSplashFrame::OnTimeout( wxTimerEvent &event )
{
//guLogMessage( wxT( "Splash timed out" ) );
Close();
}
// -------------------------------------------------------------------------------- //
void guSplashFrame::OnEraseBackground( wxEraseEvent &event )
{
wxDC * dc = event.GetDC();
if( dc )
{
dc->DrawBitmap( * m_Bitmap, 0, 0, false );
}
}
}
// -------------------------------------------------------------------------------- //
| 5,390
|
C++
|
.cpp
| 124
| 40.5
| 178
| 0.609309
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,597
|
ToggleRoundButton.cpp
|
anonbeat_guayadeque/src/ui/toggleroundbutton/ToggleRoundButton.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ToggleRoundButton.h"
#include "Images.h"
#include "Utils.h"
#include <wx/dcclient.h>
#include <wx/tglbtn.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guToggleRoundButton::guToggleRoundButton( wxWindow * parent, const wxImage &image,
const wxImage &selimage, const wxImage &hoverimage ) :
guRoundButton( parent, selimage, hoverimage )
{
m_DisBitmap = wxBitmap( image );
m_Value = false;
}
// -------------------------------------------------------------------------------- //
guToggleRoundButton::~guToggleRoundButton()
{
}
// -------------------------------------------------------------------------------- //
void guToggleRoundButton::OnPaint( wxPaintEvent &event )
{
wxPaintDC dc( this );
PrepareDC( dc );
dc.SetBackgroundMode( wxTRANSPARENT );
dc.DrawBitmap( m_MouseIsOver ? m_HoverBitmap :
( m_Value ? m_Bitmap : m_DisBitmap ),
0 + m_IsClicked, 0 + m_IsClicked, true );
}
// -------------------------------------------------------------------------------- //
void guToggleRoundButton::OnMouseEvents( wxMouseEvent &event )
{
bool NeedPaint = false;
if( m_Region.Contains( event.GetPosition() ) )
{
if( !m_MouseIsOver )
{
m_MouseIsOver = true;
//Refresh();
NeedPaint = true;
}
//guLogMessage( wxT( "Event %i %i %i" ), event.LeftDown(), event.LeftIsDown(), event.LeftUp() );
if( m_IsClicked != event.LeftIsDown() )
{
m_IsClicked = event.LeftIsDown();
//Refresh();
NeedPaint = true;
}
if( event.LeftUp() )
{
m_Value = !m_Value;
NeedPaint = true;
// Send Clicked event
wxCommandEvent ClickEvent( wxEVT_TOGGLEBUTTON, GetId() );
ClickEvent.SetEventObject( this );
ClickEvent.SetInt( m_Value );
AddPendingEvent( ClickEvent );
}
}
else
{
if( m_MouseIsOver )
{
m_MouseIsOver = false;
//Refresh();
NeedPaint = true;
}
if( m_IsClicked )
{
m_IsClicked = false;
//Refresh();
NeedPaint = true;
}
}
if( NeedPaint )
Refresh();
}
// -------------------------------------------------------------------------------- //
void guToggleRoundButton::SetValue( bool value )
{
if( value != m_Value )
{
m_Value = value;
Refresh();
}
}
}
// -------------------------------------------------------------------------------- //
| 3,745
|
C++
|
.cpp
| 108
| 28.842593
| 104
| 0.492138
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,598
|
MediaViewerLibrary.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/MediaViewerLibrary.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "MediaViewerLibrary.h"
#include "MainFrame.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guMediaViewerLibrary::guMediaViewerLibrary( wxWindow * parent, guMediaCollection &collection, const int basecommand,
guMainFrame * mainframe, const int mode, guPlayerPanel * playerpanel ) :
guMediaViewer( parent, collection, basecommand, mainframe, mode, playerpanel )
{
InitMediaViewer( mode );
}
// -------------------------------------------------------------------------------- //
guMediaViewerLibrary::~guMediaViewerLibrary()
{
}
}
// -------------------------------------------------------------------------------- //
| 1,757
|
C++
|
.cpp
| 37
| 45.864865
| 116
| 0.558085
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,599
|
MediaViewer.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/MediaViewer.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "MediaViewer.h"
#include "Accelerators.h"
#include "CopyTo.h"
#include "CoverEdit.h"
#include "DynamicPlayList.h"
#include "Images.h"
#include "ImportFiles.h"
#include "LastFM.h"
#include "LibUpdate.h"
#include "MainFrame.h"
#include "SelCoverFile.h"
#include "Settings.h"
#include "SmartMode.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Transcode.h"
#include "Utils.h"
namespace Guayadeque {
#define guMEDIAVIEWER_TIMER_TEXTSEARCH 2
#define guMEDIAVIEWER_TIMER_TEXTCHANGED 500
// -------------------------------------------------------------------------------- //
guMediaViewer::guMediaViewer( wxWindow * parent, guMediaCollection &collection, const int basecommand,
guMainFrame * mainframe, const int mode, guPlayerPanel * playerpanel ) :
wxPanel( parent ),
m_TextChangedTimer( this, guMEDIAVIEWER_TIMER_TEXTSEARCH )
{
m_MediaCollection = new guMediaCollection( collection );
m_MainFrame = mainframe;
m_PlayerPanel = playerpanel;
m_BaseCommand = basecommand;
m_ViewMode = wxNOT_FOUND;
m_ConfigPath = wxT( "mediaviewers/mediaviewer_" ) + collection.m_UniqueId;
m_UpdateThread = NULL;
m_CleanThread = NULL;
m_ContextMenuFlags = guCONTEXTMENU_DEFAULT;
m_IsDefault = false;
m_CopyToPattern = NULL;
m_UpdateCoversThread = NULL;
guLogTrace( wxT( "MediaViewer '%s' => '%s'" ), collection.m_Name.c_str(), collection.m_UniqueId.c_str() );
if( !wxDirExists( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId ) )
{
wxMkdir( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId, 0770 );
guLogMessage( wxT( "Created collection folder '%s'" ), wxString( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId ).c_str() );
}
//LoadMediaDb();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_LibPanel = NULL;
m_AlbumBrowser = NULL;
m_TreeViewPanel = NULL;
m_PlayListPanel = NULL;
m_DoneClearSearchText = false;
m_InstantSearchEnabled = Config->ReadBool( CONFIG_KEY_GENERAL_INSTANT_TEXT_SEARCH, true, CONFIG_PATH_GENERAL );
m_EnterSelectSearchEnabled = !Config->ReadBool( CONFIG_KEY_GENERAL_TEXT_SEARCH_ENTER, false, CONFIG_PATH_GENERAL );
if( !m_MediaCollection->m_DefaultCopyAction.IsEmpty() )
{
wxArrayString Options = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
int Count = Options.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
if( Options[ Index ].BeforeFirst( wxT( ':' ) ) == m_MediaCollection->m_DefaultCopyAction )
{
m_CopyToPattern = new guCopyToPattern( Options[ Index ] );
}
}
}
}
Bind( wxEVT_TIMER, &guMediaViewer::OnTextChangedTimer, this, guMEDIAVIEWER_TIMER_TEXTSEARCH );
Bind( wxEVT_MENU, &guMediaViewer::OnCleanFinished, this, ID_LIBRARY_CLEANFINISHED );
Bind( wxEVT_MENU, &guMediaViewer::OnLibraryUpdated, this, ID_LIBRARY_UPDATED );
Bind( wxEVT_MENU, &guMediaViewer::OnGenreSetSelection, this, ID_GENRE_SETSELECTION );
Bind( wxEVT_MENU, &guMediaViewer::OnArtistSetSelection, this, ID_ARTIST_SETSELECTION );
Bind( wxEVT_MENU, &guMediaViewer::OnAlbumArtistSetSelection, this, ID_ALBUMARTIST_SETSELECTION );
Bind( wxEVT_MENU, &guMediaViewer::OnComposerSetSelection, this, ID_COMPOSER_SETSELECTION );
Bind( wxEVT_MENU, &guMediaViewer::OnAlbumSetSelection, this, ID_ALBUM_SETSELECTION );
Bind( wxEVT_MENU, &guMediaViewer::OnUpdateLabels, this, ID_LABEL_UPDATELABELS );
Bind( wxEVT_MENU, &guMediaViewer::OnSmartAddTracks, this, ID_SMARTMODE_ADD_TRACKS );
}
// -------------------------------------------------------------------------------- //
guMediaViewer::~guMediaViewer()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteNum( wxT( "ViewMode" ), m_ViewMode, m_ConfigPath );
Config->WriteNum( wxT( "Filter" ), m_FilterChoice->GetSelection(), m_ConfigPath + wxT( "/albumbrowser" ) );
Config->WriteAStr( wxT( "Filter"), m_DynFilterArray, m_ConfigPath + wxT( "/albumbrowser/filters") );
Unbind( wxEVT_TIMER, &guMediaViewer::OnTextChangedTimer, this, guMEDIAVIEWER_TIMER_TEXTSEARCH );
Unbind( wxEVT_MENU, &guMediaViewer::OnCleanFinished, this, ID_LIBRARY_CLEANFINISHED );
Unbind( wxEVT_MENU, &guMediaViewer::OnLibraryUpdated, this, ID_LIBRARY_UPDATED );
Unbind( wxEVT_MENU, &guMediaViewer::OnGenreSetSelection, this, ID_GENRE_SETSELECTION );
Unbind( wxEVT_MENU, &guMediaViewer::OnArtistSetSelection, this, ID_ARTIST_SETSELECTION );
Unbind( wxEVT_MENU, &guMediaViewer::OnAlbumArtistSetSelection, this, ID_ALBUMARTIST_SETSELECTION );
Unbind( wxEVT_MENU, &guMediaViewer::OnComposerSetSelection, this, ID_COMPOSER_SETSELECTION );
Unbind( wxEVT_MENU, &guMediaViewer::OnAlbumSetSelection, this, ID_ALBUM_SETSELECTION );
Unbind( wxEVT_MENU, &guMediaViewer::OnUpdateLabels, this, ID_LABEL_UPDATELABELS );
Unbind( wxEVT_MENU, &guMediaViewer::OnSmartAddTracks, this, ID_SMARTMODE_ADD_TRACKS );
Unbind( guConfigUpdatedEvent, &guMediaViewer::OnConfigUpdated, this, ID_CONFIG_UPDATED );
m_FilterChoice->Unbind( wxEVT_CHOICE, &guMediaViewer::OnFilterSelected, this );
m_AddFilterButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnAddFilterClicked, this );
m_DelFilterButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnDelFilterClicked, this );
m_EditFilterButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnEditFilterClicked, this );
m_LibrarySelButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_AlbumBrowserSelButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_TreeViewSelButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_PlaylistsSelButton->Unbind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_SearchTextCtrl->Unbind( wxEVT_TEXT_ENTER, &guMediaViewer::OnSearchSelected, this );
m_SearchTextCtrl->Unbind( wxEVT_TEXT, &guMediaViewer::OnSearchActivated, this );
m_SearchTextCtrl->Unbind( wxEVT_SEARCHCTRL_CANCEL_BTN, &guMediaViewer::OnSearchCancelled, this );
//m_MainFrame->MediaViewerClosed( m_MediaCollection->m_UniqueId, this );
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MAINFRAME_MEDIAVIEWER_CLOSED );
CmdEvent.SetClientData( this );
wxPostEvent( m_MainFrame, CmdEvent );
if( m_UpdateCoversThread )
{
m_UpdateCoversThread->Pause();
m_UpdateCoversThread->Delete();
m_UpdateCoversThread = NULL;
}
if( m_MediaCollection )
delete m_MediaCollection;
if( m_CopyToPattern )
delete m_CopyToPattern;
if( m_Db )
delete m_Db;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::InitMediaViewer( const int mode )
{
LoadMediaDb();
CreateControls();
if( mode != wxNOT_FOUND )
{
SetViewMode( mode );
}
else
{
guConfig * Config = ( guConfig * ) guConfig::Get();
SetViewMode( Config->ReadNum( wxT( "ViewMode" ), guMEDIAVIEWER_MODE_LIBRARY, m_ConfigPath ) );
}
CreateAcceleratorTable();
m_MainFrame->MediaViewerCreated( m_MediaCollection->m_UniqueId, this );
if( m_MediaCollection->m_UpdateOnStart )
{
//UpdateLibrary();
wxCommandEvent Event( wxEVT_MENU, m_BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY );
wxPostEvent( this, Event );
}
m_SearchTextCtrl->SetFocus();
SetDropTarget( new guMediaViewerDropTarget( this ) );
Layout();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateControls( void )
{
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer * TopSizer = new wxBoxSizer( wxHORIZONTAL );
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
int FilterSelected = Config->ReadNum( wxT( "Filter" ), 0, m_ConfigPath + wxT( "/albumbrowser" ) );
m_DynFilterArray = Config->ReadAStr( wxT( "Filter"), wxEmptyString, m_ConfigPath + wxT( "/albumbrowser/filters" ) );
if( FilterSelected > ( int ) m_DynFilterArray.Count() )
FilterSelected = 0;
wxArrayString FilterNames;
FilterNames.Add( _( "All Albums" ) );
int Count = m_DynFilterArray.Count();
for( int Index = 0; Index < Count; Index++ )
{
FilterNames.Add( unescape_configlist_str( m_DynFilterArray[ Index ].BeforeFirst( wxT( ':' ) ) ) );
}
m_LibrarySelButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_mv_library ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_LibrarySelButton->SetToolTip( _( "Library view" ) );
TopSizer->Add( m_LibrarySelButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, 5 );
m_AlbumBrowserSelButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_mv_albumbrowser ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_AlbumBrowserSelButton->SetToolTip( _( "Album Browser view" ) );
TopSizer->Add( m_AlbumBrowserSelButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );
m_TreeViewSelButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_mv_treeview ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_TreeViewSelButton->SetToolTip( _( "Tree view" ) );
TopSizer->Add( m_TreeViewSelButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );
m_PlaylistsSelButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_mv_playlists ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_PlaylistsSelButton->SetToolTip( _( "Playlists" ) );
TopSizer->Add( m_PlaylistsSelButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 );
m_SearchTextCtrl = new wxSearchCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1, 28 ), wxTE_PROCESS_ENTER );
//m_SearchTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
TopSizer->Add( m_SearchTextCtrl, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
//////////////////////////
m_FiltersSizer = new wxBoxSizer( wxHORIZONTAL );
m_FilterChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilterNames, 0 );
m_FilterChoice->SetSelection( FilterSelected );
m_FilterChoice->SetToolTip( _( "View the current defined filters" ) );
//m_FilterChoice->SetMinSize( wxSize( 100, -1 ) );
m_FiltersSizer->Add( m_FilterChoice, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
m_AddFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_add ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_AddFilterButton->SetToolTip( _( "Add a new album browser filter" ) );
m_FiltersSizer->Add( m_AddFilterButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );
m_DelFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_del ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DelFilterButton->SetToolTip( _( "Delete the current selected filter" ) );
m_DelFilterButton->Enable( FilterSelected > 0 );
m_FiltersSizer->Add( m_DelFilterButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );
m_EditFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_edit ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_EditFilterButton->SetToolTip( _( "Edit the current selected filter" ) );
m_EditFilterButton->Enable( FilterSelected > 0 );
m_FiltersSizer->Add( m_EditFilterButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 );
TopSizer->Add( m_FiltersSizer, 0, wxEXPAND, 5 );
//////////////////////////////
MainSizer->Add( TopSizer, 0, wxEXPAND, 5 );
SetSizer( MainSizer );
Bind( guConfigUpdatedEvent, &guMediaViewer::OnConfigUpdated, this, ID_CONFIG_UPDATED );
m_FilterChoice->Bind( wxEVT_CHOICE, &guMediaViewer::OnFilterSelected, this );
m_AddFilterButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnAddFilterClicked, this );
m_DelFilterButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnDelFilterClicked, this );
m_EditFilterButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnEditFilterClicked, this );
m_LibrarySelButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_AlbumBrowserSelButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_TreeViewSelButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_PlaylistsSelButton->Bind( wxEVT_BUTTON, &guMediaViewer::OnViewChanged, this );
m_SearchTextCtrl->Bind( wxEVT_TEXT_ENTER, &guMediaViewer::OnSearchSelected, this );
m_SearchTextCtrl->Bind( wxEVT_TEXT, &guMediaViewer::OnSearchActivated, this );
m_SearchTextCtrl->Bind( wxEVT_SEARCHCTRL_CANCEL_BTN, &guMediaViewer::OnSearchCancelled, this );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_MENU_UPDATE_LIBRARY );
AliasAccelCmds.Add( ID_MENU_UPDATE_LIBRARYFORCED );
AliasAccelCmds.Add( ID_MENU_UPDATE_COVERS );
RealAccelCmds.Add( m_BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY );
RealAccelCmds.Add( m_BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY );
RealAccelCmds.Add( m_BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::LoadMediaDb( void )
{
m_Db = new guDbLibrary( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId + wxT( "/guayadeque.db" ) );
m_Db->SetMediaViewer( this );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_GENERAL )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_InstantSearchEnabled = Config->ReadBool( CONFIG_KEY_GENERAL_INSTANT_TEXT_SEARCH, true, CONFIG_PATH_GENERAL );
m_EnterSelectSearchEnabled = !Config->ReadBool( CONFIG_KEY_GENERAL_TEXT_SEARCH_ENTER, false, CONFIG_PATH_GENERAL );
}
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetCollection( guMediaCollection &collection, const int basecommand )
{
if( m_MediaCollection )
delete m_MediaCollection;
m_MediaCollection = new guMediaCollection( collection );
m_BaseCommand = basecommand;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnViewChanged( wxCommandEvent &event )
{
//guLogMessage( wxT( "OnViewChanged... %i" ), event.GetInt() );
if( event.GetEventObject() == m_LibrarySelButton )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
}
else if( event.GetEventObject() == m_AlbumBrowserSelButton )
{
SetViewMode( guMEDIAVIEWER_MODE_ALBUMBROWSER );
}
else if( event.GetEventObject() == m_TreeViewSelButton )
{
SetViewMode( guMEDIAVIEWER_MODE_TREEVIEW );
}
else if( event.GetEventObject() == m_PlaylistsSelButton )
{
SetViewMode( guMEDIAVIEWER_MODE_PLAYLISTS );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetPlayerPanel( guPlayerPanel * playerpanel )
{
m_PlayerPanel = playerpanel;
if( m_LibPanel )
m_LibPanel->SetPlayerPanel( playerpanel );
if( m_AlbumBrowser )
m_AlbumBrowser->SetPlayerPanel( playerpanel );
if( m_TreeViewPanel )
m_TreeViewPanel->SetPlayerPanel( playerpanel );
if( m_PlayListPanel )
m_PlayListPanel->SetPlayerPanel( playerpanel );
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::CreateLibraryView( void )
{
m_LibPanel = new guLibPanel( this, this );
m_LibPanel->SetBaseCommand( m_BaseCommand + 1 );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::CreateAlbumBrowserView( void )
{
m_AlbumBrowser = new guAlbumBrowser( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::CreateTreeView( void )
{
m_TreeViewPanel = new guTreeViewPanel( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::CreatePlayListView( void )
{
m_PlayListPanel = new guPlayListPanel( this, this );
return true;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetViewMode( const int mode )
{
guLogMessage( wxT( "SetViewMode %i => %i" ), m_ViewMode, mode );
if( mode != m_ViewMode )
{
Freeze();
switch( m_ViewMode )
{
case guMEDIAVIEWER_MODE_LIBRARY :
{
m_LibPanel->Hide();
break;
}
case guMEDIAVIEWER_MODE_ALBUMBROWSER :
{
m_AlbumBrowser->Hide();
break;
}
case guMEDIAVIEWER_MODE_TREEVIEW :
{
m_TreeViewPanel->Hide();
break;
}
case guMEDIAVIEWER_MODE_PLAYLISTS :
{
m_PlayListPanel->Hide();
break;
}
}
m_ViewMode = mode;
switch( m_ViewMode )
{
case guMEDIAVIEWER_MODE_LIBRARY :
{
if( !m_LibPanel )
{
CreateLibraryView();
GetSizer()->Add( m_LibPanel, 1, wxEXPAND|wxALL, 5 );
}
else
{
m_LibPanel->Show( true );
}
break;
}
case guMEDIAVIEWER_MODE_ALBUMBROWSER :
{
if( !m_AlbumBrowser )
{
CreateAlbumBrowserView();
GetSizer()->Add( m_AlbumBrowser, 1, wxEXPAND|wxALL, 5 );
int SelectedFilter = m_FilterChoice->GetSelection();
SetFilter( SelectedFilter ? m_DynFilterArray[ SelectedFilter - 1 ] : wxT( "" ) );
}
else
{
m_AlbumBrowser->Show( true );
}
break;
}
case guMEDIAVIEWER_MODE_TREEVIEW :
{
if( !m_TreeViewPanel )
{
CreateTreeView();
GetSizer()->Add( m_TreeViewPanel, 1, wxEXPAND|wxALL, 5 );
}
else
{
m_TreeViewPanel->Show( true );
}
break;
}
case guMEDIAVIEWER_MODE_PLAYLISTS :
{
if( !m_PlayListPanel )
{
CreatePlayListView();
GetSizer()->Add( m_PlayListPanel, 1, wxEXPAND|wxALL, 5 );
}
else
{
m_PlayListPanel->Show( true );
}
break;
}
}
m_FiltersSizer->Show( m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER );
m_FilterChoice->Enable( m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER );
m_AddFilterButton->Enable( m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER );
m_DelFilterButton->Enable( ( m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER ) && ( m_FilterChoice->GetSelection() > 0 ) );
m_EditFilterButton->Enable( ( m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER ) && ( m_FilterChoice->GetSelection() > 0 ) );
m_LibrarySelButton->Enable( m_ViewMode != guMEDIAVIEWER_MODE_LIBRARY );
m_AlbumBrowserSelButton->Enable( m_ViewMode != guMEDIAVIEWER_MODE_ALBUMBROWSER );
m_TreeViewSelButton->Enable( m_ViewMode != guMEDIAVIEWER_MODE_TREEVIEW );
m_PlaylistsSelButton->Enable( m_ViewMode != guMEDIAVIEWER_MODE_PLAYLISTS );
DoTextSearch();
Layout();
Thaw();
}
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
SetMenuState( m_ViewMode != guMEDIAVIEWER_MODE_NONE );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetMenuState( const bool enabled )
{
wxMenuBar * MenuBar = m_MainFrame->GetMenuBar();
if( MenuBar )
{
wxMenuItem * MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_COLLECTION );
if( MenuItem )
{
MenuItem->Enable( true );
MenuItem->Check( enabled );
}
bool IsEnabled = enabled && ( m_ViewMode == guMEDIAVIEWER_MODE_LIBRARY );
int VisiblePanels = IsEnabled ? m_LibPanel->VisiblePanels() : 0;
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIBRARY );
if( MenuItem )
{
MenuItem->Enable( enabled );
MenuItem->Check( IsEnabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_LABELS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_LABELS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_GENRES );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_GENRES ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_ARTISTS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_ARTISTS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_COMPOSERS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_COMPOSERS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_ALBUMARTISTS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_ALBUMARTISTS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_ALBUMS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_ALBUMS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_YEARS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_YEARS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_RATINGS );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_RATINGS ) );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_LIB_PLAYCOUNT );
if( MenuItem )
{
MenuItem->Enable( IsEnabled );
MenuItem->Check( IsEnabled && ( VisiblePanels & guPANEL_LIBRARY_PLAYCOUNT ) );
}
IsEnabled = m_ViewMode == guMEDIAVIEWER_MODE_ALBUMBROWSER;
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_ALBUMBROWSER );
if( MenuItem )
{
MenuItem->Enable( enabled );
MenuItem->Check( IsEnabled );
}
IsEnabled = m_ViewMode == guMEDIAVIEWER_MODE_TREEVIEW;
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_TREEVIEW );
if( MenuItem )
{
MenuItem->Enable( enabled );
MenuItem->Check( IsEnabled );
}
IsEnabled = m_ViewMode == guMEDIAVIEWER_MODE_PLAYLISTS;
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_PLAYLISTS );
if( MenuItem )
{
MenuItem->Enable( enabled );
MenuItem->Check( IsEnabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_ADD_PATH );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_IMPORT );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
MenuItem = MenuBar->FindItem( m_BaseCommand + guCOLLECTION_ACTION_VIEW_PROPERTIES );
if( MenuItem )
{
MenuItem->Enable( enabled );
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnSearchActivated( wxCommandEvent& event )
{
if( m_TextChangedTimer.IsRunning() )
m_TextChangedTimer.Stop();
if( m_DoneClearSearchText )
{
m_DoneClearSearchText = false;
return;
}
if( !m_InstantSearchEnabled )
return;
m_TextChangedTimer.Start( guMEDIAVIEWER_TIMER_TEXTCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnSearchCancelled( wxCommandEvent &event ) // CLEAN SEARCH STR
{
guLogMessage( wxT( "OnSearchCancelled..." ) );
m_SearchTextCtrl->Clear();
m_SearchText.Empty();
if( !m_InstantSearchEnabled )
DoTextSearch();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnSearchSelected( wxCommandEvent& event )
{
guLogMessage( wxT( "OnSearchSelected... %i %i" ), m_EnterSelectSearchEnabled, m_InstantSearchEnabled );
// perform text search immediately
if( m_TextChangedTimer.IsRunning() )
m_TextChangedTimer.Stop();
m_SearchText = m_SearchTextCtrl->GetValue();
if( !DoTextSearch() || m_EnterSelectSearchEnabled || !m_InstantSearchEnabled )
return;
// if text search was successful, possibly enqueue results
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
PlayAllTracks( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::ClearSearchText( void )
{
guLogMessage( wxT( "ClearSearchText..." ) );
m_DoneClearSearchText = true;
m_SearchTextCtrl->Clear();
m_SearchText.Empty();
m_SearchTextCtrl->ShowCancelButton( false );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::GoToSearch( void )
{
if( FindFocus() != m_SearchTextCtrl )
m_SearchTextCtrl->SetFocus();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnTextChangedTimer( wxTimerEvent &event )
{
guLogMessage( wxT( "OnTextChangedTimer..." ) );
m_SearchText = m_SearchTextCtrl->GetValue();
DoTextSearch();
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::DoTextSearch( void )
{
Freeze();
bool RetVal = false;
wxString SearchText = m_SearchText;
switch( m_ViewMode )
{
case guMEDIAVIEWER_MODE_LIBRARY :
{
RetVal = m_LibPanel->DoTextSearch( SearchText );
break;
}
case guMEDIAVIEWER_MODE_ALBUMBROWSER :
{
RetVal = m_AlbumBrowser->DoTextSearch( SearchText );
break;
}
case guMEDIAVIEWER_MODE_TREEVIEW :
{
RetVal = m_TreeViewPanel->DoTextSearch( SearchText );
break;
}
case guMEDIAVIEWER_MODE_PLAYLISTS :
{
RetVal = m_PlayListPanel->DoTextSearch( SearchText );
break;
}
}
if( RetVal )
{
m_SearchTextCtrl->ShowCancelButton( true );
}
else
{
if( SearchText.IsEmpty() )
{
m_SearchTextCtrl->ShowCancelButton( false );
}
}
Thaw();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::PlayAllTracks( const bool enqueue )
{
switch( m_ViewMode )
{
case guMEDIAVIEWER_MODE_LIBRARY :
{
m_LibPanel->PlayAllTracks( enqueue );
break;
}
case guMEDIAVIEWER_MODE_ALBUMBROWSER :
{
break;
}
case guMEDIAVIEWER_MODE_TREEVIEW :
{
break;
}
case guMEDIAVIEWER_MODE_PLAYLISTS :
{
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnAddFilterClicked( wxCommandEvent &event )
{
guDynPlayList NewPlayList;
NewPlayList.m_Name = _( "New Filter" );
guDynPlayListEditor * PlayListEditor = new guDynPlayListEditor( this, &NewPlayList, true );
if( PlayListEditor->ShowModal() == wxID_OK )
{
PlayListEditor->FillPlayListEditData();
m_DynFilterArray.Add( escape_configlist_str( NewPlayList.m_Name ) + wxT( ":" ) + NewPlayList.ToString() );
m_FilterChoice->Append( NewPlayList.m_Name );
m_FilterChoice->GetContainingSizer()->Layout();
m_FilterChoice->SetSelection( m_FilterChoice->GetCount() - 1 );
event.SetInt( m_FilterChoice->GetCount() - 1 );
OnFilterSelected( event );
}
PlayListEditor->Destroy();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnDelFilterClicked( wxCommandEvent &event )
{
int Selected = m_FilterChoice->GetSelection();
if( Selected )
{
m_DynFilterArray.RemoveAt( Selected - 1 );
m_FilterChoice->Delete( Selected );
m_FilterChoice->GetContainingSizer()->Layout();
m_FilterChoice->SetSelection( 0 );
event.SetInt( 0 );
OnFilterSelected( event );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnEditFilterClicked( wxCommandEvent &event )
{
int Selected = m_FilterChoice->GetSelection();
wxString CurFilterStr = m_DynFilterArray[ Selected - 1 ];
guDynPlayList EditPlayList;
EditPlayList.m_Name = CurFilterStr.BeforeFirst( wxT( ':' ) );
EditPlayList.FromString( CurFilterStr.AfterFirst( wxT( ':' ) ) ); // = m_DynFilter;
guDynPlayListEditor * PlayListEditor = new guDynPlayListEditor( this, &EditPlayList, true );
if( PlayListEditor->ShowModal() == wxID_OK )
{
PlayListEditor->FillPlayListEditData();
if( !EditPlayList.IsEmpty() )
{
m_DynFilterArray[ Selected - 1 ] = escape_configlist_str( EditPlayList.m_Name ) + wxT( ":" ) + EditPlayList.ToString();
m_FilterChoice->SetString( Selected, EditPlayList.m_Name );
SetFilter( m_DynFilterArray[ Selected - 1 ] );
}
else // This should never happen
{
guLogError( wxT( "Empty dynamic playlit?" ) );
}
}
PlayListEditor->Destroy();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnFilterSelected( wxCommandEvent &event )
{
int Selected = event.GetInt();
if( Selected )
{
m_DelFilterButton->Enable( true );
m_EditFilterButton->Enable( true );
SetFilter( m_DynFilterArray[ Selected - 1 ] );
}
else
{
m_DelFilterButton->Enable( false );
m_EditFilterButton->Enable( false );
SetFilter( wxEmptyString );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetFilter( const wxString &filterstr )
{
if( m_AlbumBrowser )
{
m_AlbumBrowser->SetFilter( filterstr );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateContextMenu( wxMenu * menu, const int windowid )
{
wxMenu * Menu = new wxMenu();
wxMenuItem * MenuItem;
int BaseCommand = GetBaseCommand();
int Type = GetType();
if( ( Type == guMEDIA_COLLECTION_TYPE_NORMAL ) ||
( Type == guMEDIA_COLLECTION_TYPE_PORTABLE_DEVICE ) ||
( Type == guMEDIA_COLLECTION_TYPE_IPOD ) )
{
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_ADD_PATH, _( "Add Path" ), _( "Add path to the collection" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_IMPORT, _( "Import Files" ), _( "Import files into the collection" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY, _( "Update" ), _( "Update the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY, _( "Rescan" ), _( "Rescan the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS, _( "Search Covers" ), _( "Search the collection missing covers" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_VIEW_PROPERTIES, _( "Properties" ), _( "Show collection properties" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
menu->AppendSeparator();
menu->AppendSubMenu( Menu, _( "Collection" ) );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateCopyToMenu( wxMenu * menu )
{
m_MainFrame->CreateCopyToMenu( menu );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::ShowPanel( const int id, const bool enabled )
{
if( m_ViewMode == guMEDIAVIEWER_MODE_LIBRARY )
{
m_LibPanel->ShowPanel( m_LibPanel->PanelId( id - guCOLLECTION_ACTION_VIEW_LIB_LABELS ), enabled );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::HandleCommand( const int command )
{
switch( command )
{
case guCOLLECTION_ACTION_UPDATE_LIBRARY :
{
UpdateLibrary();
break;
}
case guCOLLECTION_ACTION_RESCAN_LIBRARY :
{
UpgradeLibrary();
break;
}
case guCOLLECTION_ACTION_SEARCH_COVERS :
{
UpdateCovers();
break;
}
case guCOLLECTION_ACTION_ADD_PATH :
{
OnAddPath();
break;
}
case guCOLLECTION_ACTION_IMPORT :
{
ImportFiles();
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::EditProperties( void )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_LIBRARY );
wxPostEvent( m_MainFrame, CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpgradeLibrary( void )
{
m_MediaCollection->m_LastUpdate = 0;
UpdateLibrary();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdateLibrary( const wxString &path )
{
int GaugeId;
GaugeId = m_MainFrame->AddGauge( m_MediaCollection->m_Name, false );
if( m_UpdateThread )
{
m_UpdateThread->Pause();
m_UpdateThread->Delete();
}
m_UpdateThread = new guLibUpdateThread( this, GaugeId, path );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdateFinished( void )
{
if( m_UpdateThread )
m_UpdateThread = NULL;
SetLastUpdate();
CleanLibrary();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CleanLibrary( void )
{
if( m_CleanThread )
{
m_CleanThread->Pause();
m_CleanThread->Delete();
}
m_CleanThread = new guLibCleanThread( this );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CleanFinished( void )
{
m_CleanThread = NULL;
LibraryUpdated();
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetLastUpdate( void )
{
m_MediaCollection->m_LastUpdate = wxDateTime::Now().GetTicks();
guMediaCollection * Collection = m_MainFrame->FindCollection( m_MediaCollection->m_UniqueId );
if( Collection )
{
Collection->m_LastUpdate = m_MediaCollection->m_LastUpdate;
m_MainFrame->SaveCollections();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::LibraryUpdated( void )
{
if( m_LibPanel )
{
m_LibPanel->ReloadControls();
}
if( m_AlbumBrowser )
{
m_AlbumBrowser->RefreshAll();
}
if( m_TreeViewPanel )
{
m_TreeViewPanel->RefreshAll();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdateCovers( void )
{
int GaugeId = m_MainFrame->AddGauge( m_MediaCollection->m_Name, false );
if( m_UpdateCoversThread )
{
m_UpdateCoversThread->Pause();
m_UpdateCoversThread->Delete();
}
m_UpdateCoversThread = new guUpdateCoversThread( this, GaugeId );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdateCoversFinished( void )
{
if( m_UpdateCoversThread )
m_UpdateCoversThread = NULL;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnAddPath( void )
{
wxDirDialog * DirDialog = new wxDirDialog( this, _( "Select library path" ), wxGetHomeDir() );
if( DirDialog )
{
if( DirDialog->ShowModal() == wxID_OK )
{
wxString PathValue = DirDialog->GetPath();
if( !PathValue.IsEmpty() )
{
if( !PathValue.EndsWith( wxT( "/" ) ) )
PathValue += '/';
//guLogMessage( wxT( "LibPaths: '%s'" ), LibPaths[ 0 ].c_str() );
//guLogMessage( wxT( "Add Path: '%s'" ), PathValue.c_str() );
//guLogMessage( wxT( "Exists : %i" ), m_Db->PathExists( PathValue ) );
//guLogMessage( wxT( "Index : %i" ), LibPaths.Index( PathValue ) );
if( !CheckFileLibPath( m_MediaCollection->m_Paths, PathValue ) )
{
m_MediaCollection->m_Paths.Add( PathValue );
guMediaCollection * Collection = m_MainFrame->FindCollection( m_MediaCollection->m_UniqueId );
if( Collection )
{
Collection->m_Paths.Add( PathValue );
m_MainFrame->SaveCollections();
}
UpdateLibrary();
}
else
{
wxMessageBox( _( "This Path is already in the library" ),
_( "Adding path error" ),
wxICON_EXCLAMATION | wxOK );
}
}
}
DirDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::ImportFiles( guTrackArray * tracks )
{
if( tracks )
{
guImportFiles * ImportFiles = new guImportFiles( this, this, tracks );
if( ImportFiles )
{
if( ImportFiles->ShowModal() == wxID_OK )
{
m_MainFrame->ImportFiles( this, tracks, ImportFiles->GetCopyToOption(), ImportFiles->GetCopyToPath() );
}
else
{
delete tracks;
}
ImportFiles->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void AddImportFiles( guTrackArray * tracks, const wxString &filename )
{
//guLogMessage( wxT( "AddImportFiles : '%s'" ), filename.c_str() );
if( wxFileExists( filename ) )
{
if( guIsValidAudioFile( filename.Lower() ) )
{
guTrack * Track = new guTrack();
if( Track->ReadFromFile( filename ) )
{
Track->m_Type = guTRACK_TYPE_NOTDB;
tracks->Add( Track );
}
else
{
delete Track;
}
}
}
else if( wxDirExists( filename ) )
{
wxString FileName;
wxString DirName = filename;
wxDir Dir;
if( !DirName.EndsWith( wxT( "/" ) ) )
DirName += wxT( "/" );
Dir.Open( DirName );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( ( FileName[ 0 ] != '.' ) )
{
AddImportFiles( tracks, DirName + FileName );
}
} while( Dir.GetNext( &FileName ) );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::ImportFiles( const wxArrayString &files )
{
int Count = files.Count();
if( Count )
{
guTrackArray * Tracks = new guTrackArray();
for( int Index = 0; Index < Count; Index++ )
{
AddImportFiles( Tracks, files[ Index ] );
}
ImportFiles( Tracks );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SaveLayout( wxXmlNode * xmlnode )
{
// MediaViewer
//
wxXmlNode * XmlNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "mediaviewer" ) );
wxXmlAttribute * Property = new wxXmlAttribute( wxT( "name" ), m_MediaCollection->m_Name,
new wxXmlAttribute( wxT( "id" ), m_MediaCollection->m_UniqueId,
new wxXmlAttribute( wxT( "mode" ), wxString::Format( wxT( "%i" ), m_ViewMode ),
NULL ) ) );
XmlNode->SetAttributes( Property );
if( m_LibPanel )
{
m_LibPanel->SaveLayout( XmlNode, wxT( "library" ) );
}
if( m_TreeViewPanel )
{
m_TreeViewPanel->SaveLayout( XmlNode, wxT( "tree" ) );
}
if( m_PlayListPanel )
{
m_PlayListPanel->SaveLayout( XmlNode, wxT( "playlist" ) );
}
xmlnode->AddChild( XmlNode );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::LoadLayout( wxXmlNode * xmlnode )
{
if( xmlnode && xmlnode->GetName() == wxT( "mediaviewer" ) )
{
wxString Mode;
long ViewMode;
xmlnode->GetAttribute( wxT( "mode" ), &Mode );
wxXmlNode * XmlNode = xmlnode->GetChildren();
while( XmlNode )
{
wxString NodeName = XmlNode->GetName();
if( NodeName == wxT( "library" ) )
{
if( !m_LibPanel )
{
m_LibPanel = new guLibPanel( this, this );
m_LibPanel->SetBaseCommand( m_BaseCommand + 1 );
GetSizer()->Add( m_LibPanel, 1, wxEXPAND, 5 );
}
m_LibPanel->Hide();
m_LibPanel->LoadLayout( XmlNode );
}
else if( NodeName == wxT( "tree" ) )
{
if( !m_TreeViewPanel )
{
m_TreeViewPanel = new guTreeViewPanel( this, this );
GetSizer()->Add( m_TreeViewPanel, 1, wxEXPAND, 5 );
}
m_TreeViewPanel->Hide();
m_TreeViewPanel->LoadLayout( XmlNode );
}
else if( NodeName == wxT( "playlist" ) )
{
if( !m_PlayListPanel )
{
m_PlayListPanel = new guPlayListPanel( this, this );
GetSizer()->Add( m_PlayListPanel, 1, wxEXPAND, 5 );
}
m_PlayListPanel->Hide();
m_PlayListPanel->LoadLayout( XmlNode );
}
XmlNode = XmlNode->GetNext();
}
if( Mode.ToLong( &ViewMode ) )
{
SetViewMode( guMEDIAVIEWER_MODE_NONE );
SetViewMode( ViewMode );
}
}
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewer::GetSelInfo( void )
{
wxLongLong SelCount = 0;
wxLongLong SelLength = 0;
wxLongLong SelSize = 0;
switch( m_ViewMode )
{
case guMEDIAVIEWER_MODE_LIBRARY :
{
m_Db->GetTracksCounters( &SelCount, &SelLength, &SelSize );
wxString SelInfo = wxString::Format( wxT( "%llu " ), SelCount.GetValue() );
SelInfo += SelCount == 1 ? _( "track" ) : _( "tracks" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( SelLength.GetValue() ).c_str(),
SizeToString( SelSize.GetValue() ).c_str() );
return SelInfo;
}
case guMEDIAVIEWER_MODE_ALBUMBROWSER :
{
return m_AlbumBrowser->GetSelInfo();
}
case guMEDIAVIEWER_MODE_TREEVIEW :
{
m_TreeViewPanel->GetTreeViewCounters( &SelCount, &SelLength, &SelSize );
if( SelCount > 0 )
{
wxString SelInfo = wxString::Format( wxT( "%llu " ), SelCount.GetValue() );
SelInfo += SelCount == 1 ? _( "track" ) : _( "tracks" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( SelLength.GetValue() ).c_str(),
SizeToString( SelSize.GetValue() ).c_str() );
return SelInfo;
}
break;
}
case guMEDIAVIEWER_MODE_PLAYLISTS :
{
if( m_PlayListPanel->GetPlayListCounters( &SelCount, &SelLength, &SelSize ) )
{
wxString SelInfo = wxString::Format( wxT( "%llu " ), SelCount.GetValue() );
SelInfo += SelCount == 1 ? _( "track" ) : _( "tracks" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( SelLength.GetValue() ).c_str(),
SizeToString( SelSize.GetValue() ).c_str() );
return SelInfo;
}
break;
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdatedTrack( const int updatedby, const guTrack * track )
{
if( m_LibPanel )
m_LibPanel->UpdatedTrack( track );
if( m_TreeViewPanel )
m_TreeViewPanel->UpdatedTrack( track );
if( m_PlayListPanel )
m_PlayListPanel->UpdatedTrack( track );
//if( m_AlbumBrowser )
// m_AlbumBrowser->UpdatedTracks( tracks );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdatedTracks( const int updatedby, const guTrackArray * tracks )
{
if( m_LibPanel )
m_LibPanel->UpdatedTracks( tracks );
if( m_TreeViewPanel )
m_TreeViewPanel->UpdatedTracks( tracks );
if( m_PlayListPanel )
m_PlayListPanel->UpdatedTracks( tracks );
if( m_MainFrame )
{
m_MainFrame->UpdatedTracks( guUPDATED_TRACKS_MEDIAVIEWER, tracks );
}
//if( m_AlbumBrowser )
// m_AlbumBrowser->UpdatedTracks( tracks );
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::CopyTo( guTrack * track, guCopyToAction ©toaction, wxString &filename, const int index )
{
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::DownloadAlbumCover( const int albumid )
{
wxString AlbumName;
wxString ArtistName;
wxString AlbumPath;
if( !m_Db->GetAlbumInfo( albumid, &AlbumName, &ArtistName, &AlbumPath ) )
{
wxMessageBox( _( "Could not find the Album in the songs library.\n"\
"You should update the library." ), _( "Error" ), wxICON_ERROR | wxOK );
return;
}
AlbumName = RemoveSearchFilters( AlbumName );
guCoverEditor * CoverEditor = new guCoverEditor( this, ArtistName, AlbumName, AlbumPath );
if( CoverEditor )
{
if( CoverEditor->ShowModal() == wxID_OK )
{
//guLogMessage( wxT( "About to download cover from selected url" ) );
wxImage * CoverImage = CoverEditor->GetSelectedCoverImage();
if( CoverImage )
{
wxArrayString SearchCovers = GetCoverWords();
wxString CoverName = AlbumPath + ( SearchCovers.Count() ? SearchCovers[ 0 ] : wxT( "cover" ) ) + wxT( ".jpg" );
CoverImage->SaveFile( CoverName, wxBITMAP_TYPE_JPEG );
SetAlbumCover( albumid, CoverName );
if( CoverEditor->EmbedToFiles() )
{
EmbedAlbumCover( albumid );
}
}
}
CoverEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SelectAlbumCover( const int albumid )
{
guSelCoverFile * SelCoverFile = new guSelCoverFile( this, this, albumid );
if( SelCoverFile )
{
if( SelCoverFile->ShowModal() == wxID_OK )
{
wxString CoverFile = SelCoverFile->GetSelFile();
if( !CoverFile.IsEmpty() )
{
if( SetAlbumCover( albumid, SelCoverFile->GetAlbumPath(), CoverFile ) )
{
if( SelCoverFile->EmbedToFiles() )
{
EmbedAlbumCover( albumid );
}
}
}
}
SelCoverFile->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::EmbedAlbumCover( const int albumid )
{
wxImage * CoverImage = NULL;
int CoverId = m_Db->GetAlbumCoverId( albumid );
if( CoverId > 0 )
{
wxString CoverPath = m_Db->GetCoverPath( CoverId );
CoverImage = new wxImage( CoverPath, wxBITMAP_TYPE_ANY );
if( CoverImage )
{
if( !CoverImage->IsOk() )
{
delete CoverImage;
return;
}
guImageResize( CoverImage, 600 );
}
else
return;
}
guTrackArray AlbumTracks;
wxArrayInt Albums;
Albums.Add( albumid );
m_Db->GetAlbumsSongs( Albums, &AlbumTracks );
NormalizeTracks( &AlbumTracks );
int TrackIndex;
int TrackCount;
if( ( TrackCount = AlbumTracks.Count() ) )
{
for( TrackIndex = 0; TrackIndex < TrackCount; TrackIndex++ )
{
if( !AlbumTracks[ TrackIndex ].m_Offset )
guTagSetPicture( AlbumTracks[ TrackIndex ].m_FileName, CoverImage );
}
}
if( CoverImage )
delete CoverImage;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::SetAlbumCover( const int albumid, const wxString &coverpath, const bool update )
{
m_Db->SetAlbumCover( albumid, coverpath );
if( update )
AlbumCoverChanged( albumid );
return true;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewer::GetCoverName( const int albumid )
{
return m_MediaCollection->m_CoverWords.Count() ? m_MediaCollection->m_CoverWords[ 0 ] : wxT( "cover" );
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::SetAlbumCover( const int albumid, const wxString &albumpath, wxImage * coverimg )
{
wxString CoverName = albumpath + GetCoverName( albumid ) + wxT( ".jpg" );
int MaxSize = GetCoverMaxSize();
if( MaxSize )
{
coverimg->Rescale( MaxSize, MaxSize, wxIMAGE_QUALITY_HIGH );
}
if( coverimg->SaveFile( CoverName, wxBITMAP_TYPE_JPEG ) )
{
SetAlbumCover( albumid, CoverName );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::SetAlbumCover( const int albumid, const wxString &albumpath, wxString &coverpath )
{
wxString CoverName = albumpath + GetCoverName( albumid ) + wxT( ".jpg" );
int MaxSize = GetCoverMaxSize();
wxURI Uri( coverpath );
if( Uri.IsReference() )
{
wxImage CoverImage( coverpath );
if( CoverImage.IsOk() )
{
if( MaxSize )
{
CoverImage.Rescale( MaxSize, MaxSize, wxIMAGE_QUALITY_HIGH );
}
if( ( coverpath == CoverName ) || CoverImage.SaveFile( CoverName, wxBITMAP_TYPE_JPEG ) )
{
SetAlbumCover( albumid, CoverName );
return true;
}
}
else
{
guLogError( wxT( "Could not load the image '%s'" ), coverpath.c_str() );
}
}
else
{
if( DownloadImage( coverpath, CoverName, GetCoverType(), MaxSize, MaxSize ) )
{
SetAlbumCover( albumid, CoverName );
return true;
}
else
{
guLogError( wxT( "Failed to download file '%s'" ), coverpath.c_str() );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::DeleteAlbumCover( const int albumid )
{
int CoverId = m_Db->GetAlbumCoverId( albumid );
if( CoverId > 0 )
{
wxString CoverPath = m_Db->GetCoverPath( CoverId );
if( !wxRemoveFile( CoverPath ) )
{
guLogError( wxT( "Could not remove the cover file '%s'" ), CoverPath.c_str() );
}
}
SetAlbumCover( albumid, wxEmptyString, false );
AlbumCoverChanged( albumid, true );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::DeleteAlbumCover( const wxArrayInt &albumids )
{
int Count = albumids.Count();
for( int Index = 0; Index < Count; Index++ )
{
DeleteAlbumCover( albumids[ Index ] );
}
if( Count )
AlbumCoverChanged( albumids[ 0 ], true );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::AlbumCoverChanged( const int albumid, const bool deleted )
{
if( m_LibPanel )
{
m_LibPanel->AlbumCoverChanged();
}
if( m_AlbumBrowser )
{
m_AlbumBrowser->AlbumCoverChanged( albumid );
}
wxCommandEvent evt( wxEVT_MENU, ID_ALBUM_COVER_CHANGED );
evt.SetInt( albumid );
evt.SetExtraLong( deleted );
evt.SetClientData( this );
wxPostEvent( m_MainFrame, evt );
}
// -------------------------------------------------------------------------------- //
wxImage * guMediaViewer::GetAlbumCover( const int albumid, int &coverid, wxString &coverpath,
const wxString &artistname, const wxString &albumname )
{
if( !coverid )
coverid = m_Db->GetAlbumCoverId( albumid );
if( coverid )
{
coverpath = m_Db->GetCoverPath( coverid );
if( wxFileExists( coverpath ) )
{
wxImage * CoverImage = new wxImage( coverpath, wxBITMAP_TYPE_JPEG );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
delete CoverImage;
}
}
}
return NULL;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::FindMissingCover( const int albumid, const wxString &artistname,
const wxString &albumname, const wxString &albumpath )
{
bool RetVal = false;
guLastFM * LastFM = new guLastFM();
if( LastFM )
{
wxString AlbumName;
guAlbumInfo AlbumInfo;
// Remove from album name expressions like (cd1),(cd2) etc
AlbumName = RemoveSearchFilters( albumname );
AlbumInfo = LastFM->AlbumGetInfo( artistname, albumname );
// Try to download the cover
if( LastFM->IsOk() )
{
if( !AlbumInfo.m_ImageLink.IsEmpty() )
{
//guLogMessage( wxT( "ImageLink : %s" ), AlbumInfo.ImageLink.c_str() );
// Save the cover into the target directory.
// Changed to DownloadImage to convert all images to jpg
wxString CoverName = albumpath + GetCoverName( albumid ) + wxT( ".jpg" );
if( !DownloadImage( AlbumInfo.m_ImageLink, CoverName ) )
{
guLogWarning( wxT( "Could not download cover file" ) );
}
else
{
// DownloadedCovers++;
m_Db->SetAlbumCover( albumid, CoverName );
//guLogMessage( wxT( "Cover file downloaded for %s - %s" ), Artist.c_str(), AlbumName.c_str() );
RetVal = true;
}
}
}
else
{
// There was en error...
guLogError( wxT( "Error getting the cover for %s - %s (%u)" ),
artistname.c_str(),
albumname.c_str(),
LastFM->GetLastError() );
}
delete LastFM;
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetSelection( const int type, const int id )
{
if( m_ViewMode != guMEDIAVIEWER_MODE_LIBRARY )
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
guLogMessage( wxT( "SetSelection( %i, %i )" ), type, id );
m_LibPanel->SetSelection( type, id );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::PlayListUpdated( void )
{
if( IsDefault() )
{
wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
wxPostEvent( m_MainFrame, evt );
}
}
// -------------------------------------------------------------------------------- //
bool guIsDirectoryEmpty( const wxString &path )
{
wxString FileName;
wxString Path= path;
wxDir Dir;
if( !Path.EndsWith( wxT( "/" ) ) )
Path += wxT( "/" );
Dir.Open( Path );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( FileName == wxT( "." ) ||
FileName == wxT( ".." ) )
continue;
if( Dir.Exists( Path + FileName ) )
{
if( !guIsDirectoryEmpty( Path + FileName ) )
return false;
}
else
{
return false;
}
} while( Dir.GetNext( &FileName ) );
}
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guRmDirRecursive( const wxString &path )
{
wxString FileName;
wxString Path= path;
wxDir Dir;
if( !Path.EndsWith( wxT( "/" ) ) )
Path += wxT( "/" );
Dir.Open( Path );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( FileName == wxT( "." ) ||
FileName == wxT( ".." ) )
continue;
if( Dir.Exists( Path + FileName ) )
{
if( !guRmDirRecursive( Path + FileName ) )
return false;
}
else
{
return false;
}
} while( Dir.GetNext( &FileName ) );
}
}
if( !wxRmdir( Path ) )
{
guLogMessage( wxT( "Could not delete the dir %s" ), Path.c_str() );
return false;
}
return true;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::DeleteTracks( const guTrackArray * tracks )
{
m_Db->DeleteLibraryTracks( tracks, false );
//
wxArrayString DeletePaths;
int Count = tracks->Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &CurTrack = tracks->Item( Index );
if( CurTrack.m_Offset )
continue;
if( DeletePaths.Index( wxPathOnly( CurTrack.m_FileName ) ) == wxNOT_FOUND )
{
DeletePaths.Add( wxPathOnly( CurTrack.m_FileName ) );
}
if( !wxRemoveFile( CurTrack.m_FileName ) )
{
guLogMessage( wxT( "Error deleting '%s'" ), CurTrack.m_FileName.c_str() );
}
guLogMessage( wxT( "Deleted '%s'" ), CurTrack.m_FileName.c_str() );
}
if( ( Count = DeletePaths.Count() ) )
{
wxArrayString LibPaths = GetPaths();
for( int Index = 0; Index < ( int ) LibPaths.Count(); Index++ )
{
guLogMessage( wxT( "Libath: %s"), LibPaths[ Index ].c_str() );
}
for( int Index = 0; Index < Count; Index++ )
{
wxString CurPath = DeletePaths[ Index ];
while( !CurPath.IsEmpty() && LibPaths.Index( CurPath + wxT( "/" ) ) == wxNOT_FOUND )
{
guLogMessage( wxT( "Deleting '%s'" ), CurPath.c_str() );
if( guIsDirectoryEmpty( CurPath ) )
{
if( !guRmDirRecursive( CurPath ) )
{
guLogMessage( wxT( "Error removing dir '%s'" ), DeletePaths[ Index ].c_str() );
break;
}
}
else
{
break;
}
CurPath = CurPath.BeforeLast( wxT( '/' ) );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdateTracks( const guTrackArray &tracks, const guImagePtrArray &images,
const wxArrayString &lyrics, const wxArrayInt &changedflags )
{
guUpdateTracks( tracks, images, lyrics, changedflags );
m_Db->UpdateSongs( &tracks, changedflags );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnGenreSetSelection( wxCommandEvent &event )
{
wxArrayInt * genres = ( wxArrayInt * ) event.GetClientData();
if( genres )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
m_LibPanel->SelectGenres( genres );
delete genres;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnArtistSetSelection( wxCommandEvent &event )
{
wxArrayInt * artists = ( wxArrayInt * ) event.GetClientData();
if( artists )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
m_LibPanel->SelectArtists( artists );
delete artists;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnAlbumArtistSetSelection( wxCommandEvent &event )
{
wxArrayInt * Ids = ( wxArrayInt * ) event.GetClientData();
if( Ids )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
m_LibPanel->SelectAlbumArtists( Ids );
delete Ids;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnComposerSetSelection( wxCommandEvent &event )
{
wxArrayInt * Ids = ( wxArrayInt * ) event.GetClientData();
if( Ids )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
m_LibPanel->SelectComposers( Ids );
delete Ids;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnAlbumSetSelection( wxCommandEvent &event )
{
wxArrayInt * albums = ( wxArrayInt * ) event.GetClientData();
if( albums )
{
SetViewMode( guMEDIAVIEWER_MODE_LIBRARY );
m_LibPanel->SelectAlbums( albums );
delete albums;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnUpdateLabels( wxCommandEvent &event )
{
if( m_LibPanel )
{
m_LibPanel->UpdateLabels();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::UpdatePlaylists( void )
{
wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
wxPostEvent( m_MainFrame, evt );
if( m_PlayListPanel )
{
m_PlayListPanel->UpdatePlaylists();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::SetTracksRating( guTrackArray &tracks, const int rating )
{
int Count = tracks.Count();
if( Count )
{
wxArrayInt ChangedFlags;
ChangedFlags.Add( guTRACK_CHANGED_DATA_RATING, Count );
for( int Index = 0; Index < Count; Index++ )
{
tracks[ Index ].m_Rating = rating;
}
if( GetEmbeddMetadata() )
{
guImagePtrArray Images;
wxArrayString Lyrics;
guUpdateTracks( tracks, Images, Lyrics, ChangedFlags );
}
m_Db->SetTracksRating( &tracks, rating );
UpdatedTracks( guUPDATED_TRACKS_NONE, &tracks );
}
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewer::AudioPath( void )
{
if( m_CopyToPattern && !m_CopyToPattern->m_Path.IsEmpty() )
{
return m_CopyToPattern->m_Path;
}
if( m_MediaCollection->m_Paths.Count() )
return m_MediaCollection->m_Paths[ 0 ];
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewer::Pattern( void )
{
if( m_CopyToPattern )
{
return m_CopyToPattern->m_Pattern;
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::AudioFormats( void )
{
return guPORTABLEMEDIA_AUDIO_FORMAT_ALL;
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::TranscodeFormat( void )
{
if( m_CopyToPattern )
{
return m_CopyToPattern->m_Format;
}
return guTRANSCODE_FORMAT_KEEP;
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::TranscodeScope( void )
{
return guPORTABLEMEDIA_TRANSCODE_SCOPE_NOT_SUPPORTED;
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::TranscodeQuality( void )
{
if( m_CopyToPattern )
{
return m_CopyToPattern->m_Quality;
}
return guTRANSCODE_QUALITY_KEEP;
}
// -------------------------------------------------------------------------------- //
int guMediaViewer::PlaylistFormats( void )
{
return 0;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewer::PlaylistPath( void )
{
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewer::MoveFiles( void )
{
if( m_CopyToPattern )
{
return m_CopyToPattern->m_MoveFiles;
}
return false;
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::OnSmartAddTracks( wxCommandEvent &event )
{
guLogTrace( wxT( "guMediaViewer::OnSmartAddTracks" ) );
guTrackArray * Tracks = ( guTrackArray * ) event.GetClientData();
if( Tracks )
{
wxArrayInt TrackIds;
int Count = Tracks->Count();
for( int Index = 0; Index < Count; Index++ )
{
TrackIds.Add( Tracks->Item( Index ).m_SongId );
}
guListItems PlayLists;
if( m_SmartPlaylistId == wxNOT_FOUND )
{
m_Db->CreateStaticPlayList( m_SmartPlaylistName, TrackIds );
}
else
{
m_Db->AppendStaticPlayList( m_SmartPlaylistId, TrackIds );
}
UpdatePlaylists();
delete Tracks;
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateSmartPlaylist( const wxString &artistname, const wxString &trackname )
{
wxString PlaylistName = artistname + wxT( " " ) + trackname + wxT( " " );
PlaylistName += _( " smart playlist" );
guGenSmartPlaylist * GenSmartPlaylist = new guGenSmartPlaylist( this, this, PlaylistName );
if( GenSmartPlaylist )
{
if( GenSmartPlaylist->ShowModal() == wxID_OK )
{
m_SmartArtistsList.Clear();
m_SmartTracksList.Clear();
int GaugeId = m_MainFrame->AddGauge( _( "Playlist" ) );
guSmartModeThread * SmartModeThread = new guSmartModeThread( m_Db, this,
artistname, trackname,
&m_SmartTracksList, &m_SmartArtistsList,
100, 20,
GenSmartPlaylist->GetLimitValue(), GenSmartPlaylist->GetLimitType(),
GenSmartPlaylist->GetAllowFilter(), GenSmartPlaylist->GetDenyFilter(),
GaugeId );
if( !SmartModeThread )
guLogMessage( wxT( "Could not create the smart mode thread" ) );
m_SmartPlaylistId = GenSmartPlaylist->GetPlayListId();
m_SmartPlaylistName = GenSmartPlaylist->GetPlaylistName();
}
GenSmartPlaylist->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateBestOfPlaylist( const guTrack &track )
{
wxString ArtistName = track.m_AlbumArtist;
if( ArtistName.IsEmpty() )
ArtistName = track.m_ArtistName;
CreateBestOfPlaylist( ArtistName );
}
// -------------------------------------------------------------------------------- //
void guMediaViewer::CreateBestOfPlaylist( const wxString &artistname )
{
wxString PlaylistName = _( "The best of " ) + artistname;
wxLogMessage( wxT( "Creating the playlist: %s" ), PlaylistName );
guLastFM * lfm = new guLastFM();
guTopTrackInfoArray TopTracks = lfm->ArtistGetTopTracks( artistname );
if( !TopTracks.IsEmpty() )
{
wxArrayInt TrackIds;
int Count = TopTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTopTrackInfo TopTrack = TopTracks[ Index ];
int TrackId = m_Db->FindTrack( TopTrack.m_ArtistName, TopTrack.m_TrackName );
if( TrackId != wxNOT_FOUND )
{
TrackIds.Add( TrackId );
}
}
if( !TrackIds.IsEmpty() )
{
m_Db->CreateStaticPlayList( PlaylistName, TrackIds );
UpdatePlaylists();
}
else
{
wxLogMessage( _( "No tracks found for %s." ), PlaylistName );
}
}
else
{
wxLogMessage( _( "Best tracks for '%s' not found." ), artistname );
}
delete lfm;
}
// -------------------------------------------------------------------------------- //
// guUpdateCoversThread
// -------------------------------------------------------------------------------- //
guUpdateCoversThread::guUpdateCoversThread( guMediaViewer * mediaviewer, int gaugeid ) : wxThread()
{
m_MediaViewer = mediaviewer;
m_GaugeId = gaugeid;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guUpdateCoversThread::~guUpdateCoversThread()
{
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
event.SetInt( m_GaugeId );
wxPostEvent( m_MediaViewer->GetMainFrame(), event );
if( !TestDestroy() )
{
m_MediaViewer->UpdateCoversFinished();
}
}
// -------------------------------------------------------------------------------- //
guUpdateCoversThread::ExitCode guUpdateCoversThread::Entry()
{
guCoverInfos MissingCovers;
wxCommandEvent event( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
event.SetInt( m_GaugeId );
int Count = m_MediaViewer->GetDb()->GetEmptyCovers( MissingCovers );
if( Count )
{
event.SetExtraLong( Count );
wxPostEvent( m_MediaViewer->GetMainFrame(), event );
event.SetId( ID_STATUSBAR_GAUGE_UPDATE );
event.SetInt( m_GaugeId );
for( int Index = 0; Index < Count; Index++ )
{
guCoverInfo &CurrentCover = MissingCovers[ Index ];
m_MediaViewer->FindMissingCover( CurrentCover.m_AlbumId, CurrentCover.m_ArtistName, CurrentCover.m_AlbumName, CurrentCover.m_AlbumPath );
event.SetExtraLong( Index );
wxPostEvent( m_MediaViewer->GetMainFrame(), event );
Sleep( 500 ); // Dont hammer cover service provider
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guMediaViewerDropTarget
// -------------------------------------------------------------------------------- //
guMediaViewerDropTarget::guMediaViewerDropTarget( guMediaViewer * mediaviewer ) : wxDropTarget()
{
m_MediaViewer = mediaviewer;
wxDataObjectComposite * DataObject = new wxDataObjectComposite();
wxCustomDataObject * TracksDataObject = new wxCustomDataObject( wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) );
DataObject->Add( TracksDataObject, true );
wxFileDataObject * FileDataObject = new wxFileDataObject();
DataObject->Add( FileDataObject, false );
SetDataObject( DataObject );
}
// -------------------------------------------------------------------------------- //
guMediaViewerDropTarget::~guMediaViewerDropTarget()
{
}
// -------------------------------------------------------------------------------- //
wxDragResult guMediaViewerDropTarget::OnData( wxCoord x, wxCoord y, wxDragResult def )
{
if( def == wxDragError || def == wxDragNone || def == wxDragCancel )
return def;
if( !GetData() )
{
guLogMessage( wxT( "Error getting drop data" ) );
return wxDragError;
}
guDataObjectComposite * DataObject = ( guDataObjectComposite * ) m_dataObject;
wxDataFormat ReceivedFormat = DataObject->GetReceivedFormat();
//guLogMessage( wxT( "ReceivedFormat: '%s'" ), ReceivedFormat.GetId().c_str() );
if( ReceivedFormat == wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) )
{
guTrackArray * Tracks;
if( !DataObject->GetDataHere( ReceivedFormat, &Tracks ) )
{
guLogMessage( wxT( "Error getting tracks data..." ) );
}
else
{
m_MediaViewer->ImportFiles( new guTrackArray( * Tracks ) );
}
}
else if( ReceivedFormat == wxDataFormat( wxDF_FILENAME ) )
{
wxFileDataObject * FileDataObject = ( wxFileDataObject * ) DataObject->GetDataObject( wxDataFormat( wxDF_FILENAME ) );
if( FileDataObject )
{
m_MediaViewer->ImportFiles( FileDataObject->GetFilenames() );
}
}
return def;
}
}
// -------------------------------------------------------------------------------- //
| 78,834
|
C++
|
.cpp
| 2,019
| 31.422486
| 169
| 0.539859
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,600
|
AudioCdPanel.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/audiocd/AudioCdPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AudioCdPanel.h"
#include "Accelerators.h"
#include "Config.h"
#include "EditWithOptions.h"
#include "EventCommandIds.h"
#include "Images.h"
#include "MainFrame.h"
#include "MusicBrainz.h"
#include <gst/gst.h>
#include <gst/tag/tag.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
class guAudioCdReadTocThread : public wxThread
{
protected :
guAudioCdPanel * m_AudioCdPanel;
GstElement * m_Pipeline;
bool m_Running;
guTrackArray m_CdTracks;
wxString m_MBDiscId;
bool BuildPipeline( void );
public :
guAudioCdReadTocThread( guAudioCdPanel * audiocdpanel );
~guAudioCdReadTocThread();
virtual ExitCode Entry();
void Stop( void );
guTrackArray & GetCdTracks( void ) { return m_CdTracks; }
void SetMbDiscId( const wxString &mbdiscid );
};
// -------------------------------------------------------------------------------- //
extern "C" {
// -------------------------------------------------------------------------------- //
static gboolean gst_bus_async_callback( GstBus * bus, GstMessage * message, guAudioCdReadTocThread * pobj )
{
//guLogMessage( wxT( "Got gstreamer message %u" ), GST_MESSAGE_TYPE( message ) );
switch( GST_MESSAGE_TYPE( message ) )
{
case GST_MESSAGE_ERROR :
{
GError * err;
gchar * debug;
gst_message_parse_error( message, &err, &debug );
guLogError( wxT( "Gstreamer error '%s'" ), wxString( err->message, wxConvUTF8 ).c_str() );
g_error_free( err );
g_free( debug );
pobj->Stop();
break;
}
case GST_MESSAGE_EOS :
{
//guLogMessage( wxT( "EOS Detected..." ) );
pobj->Stop();
break;
}
case GST_MESSAGE_TOC :
{
GstToc * Toc;
gst_message_parse_toc( message, &Toc, NULL );
if( Toc )
{
guTrackArray & CdTracks = pobj->GetCdTracks();
GList * TocEntries = gst_toc_get_entries( Toc );
if( TocEntries && CdTracks.Count() <= g_list_length( TocEntries ) )
{
int Index = 0;
for( GList * Node = TocEntries; Node != NULL; Node = Node->next )
{
GstTocEntry * TocEntry = static_cast<GstTocEntry*>( Node->data );
gint64 Length = 0;
gint64 Start;
gint64 Stop;
if( gst_toc_entry_get_start_stop_times( TocEntry, &Start, &Stop ) )
Length = Stop - Start;
CdTracks[ Index ].m_Length = ( Length / GST_MSECOND );
Index++;
}
}
}
break;
}
case GST_MESSAGE_TAG :
{
GstTagList * tags = NULL;
gst_message_parse_tag( message, &tags );
char * MBDiscId = NULL;
if( gst_tag_list_get_string( tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID, &MBDiscId ) )
{
pobj->SetMbDiscId( wxString( MBDiscId, wxConvUTF8 ) );
g_free( MBDiscId );
gst_tag_list_free( tags );
}
break;
}
default :
break;
}
return TRUE;
}
}
// -------------------------------------------------------------------------------- //
guAudioCdReadTocThread::guAudioCdReadTocThread( guAudioCdPanel * audiocdpanel )
{
m_AudioCdPanel = audiocdpanel;
m_Running = false;
m_Pipeline = NULL;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guAudioCdReadTocThread::~guAudioCdReadTocThread()
{
if( GST_IS_ELEMENT( m_Pipeline ) )
{
gst_element_set_state( m_Pipeline, GST_STATE_NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_remove_watch( bus );
gst_object_unref( G_OBJECT( bus ) );
gst_object_unref( GST_OBJECT( m_Pipeline ) );
m_Pipeline = NULL;
}
if( !TestDestroy() )
{
m_AudioCdPanel->SetAudioCdTracks( m_CdTracks );
}
}
// -------------------------------------------------------------------------------- //
bool guAudioCdReadTocThread::BuildPipeline( void )
{
m_Pipeline = gst_pipeline_new( "guPipeline" );
if( GST_IS_ELEMENT( m_Pipeline ) )
{
GstElement * src = gst_element_make_from_uri( GST_URI_SRC, "cdda://", "guAudioCdSrc", NULL );
if( GST_IS_ELEMENT( src ) )
{
if( gst_element_set_state( src, GST_STATE_READY ) == GST_STATE_CHANGE_FAILURE ||
gst_element_set_state( src, GST_STATE_PAUSED ) == GST_STATE_CHANGE_FAILURE )
{
guLogMessage( wxT( "Could not start the cdda pipeline." ) );
gst_element_set_state( src, GST_STATE_NULL );
}
else
{
GstFormat Format = gst_format_get_by_nick( "track" );
GstFormat OutFormat = Format;
gint64 TrackCount = 0;
if( !gst_element_query_duration( src, OutFormat, &TrackCount ) || OutFormat != Format )
{
guLogMessage( wxT( "Error reading tracks from cdda element" ) );
}
else
{
// Create the tracks...
for( int Index = 0; Index < TrackCount; Index++ )
{
guTrack * CdTrack = new guTrack();
if( CdTrack )
{
CdTrack->m_SongId = Index + 1;
CdTrack->m_Number = Index + 1;
CdTrack->m_Type = guTRACK_TYPE_AUDIOCD;
CdTrack->m_FileName = wxString::Format( wxT( "cdda://%i" ), CdTrack->m_Number );
CdTrack->m_SongName = wxString::Format( wxT( "Track%03i" ), CdTrack->m_Number );
m_CdTracks.Add( CdTrack );
}
else
{
guLogMessage( wxT( "Could not create cd track object." ) );
}
}
// Need musicbrainz diskid tag
gst_tag_register_musicbrainz_tags();
GstElement * fake = gst_element_factory_make( "fakesink", "guFakeSink" );
if( GST_IS_ELEMENT( fake ) )
{
g_object_set( G_OBJECT( fake ), "sync", 0, NULL );
gst_bin_add_many( GST_BIN( m_Pipeline ), src, fake, NULL );
g_object_set( m_Pipeline, "async-handling", true, NULL );
GstBus * bus = gst_pipeline_get_bus( GST_PIPELINE( m_Pipeline ) );
gst_bus_add_watch( bus, ( GstBusFunc ) gst_bus_async_callback, this );
gst_object_unref( G_OBJECT( bus ) );
if( gst_element_link( src, fake ) )
{
gst_element_set_state( m_Pipeline, GST_STATE_READY );
gst_element_set_state( m_Pipeline, GST_STATE_PAUSED );
return true;
}
else
{
guLogMessage( wxT( "Error linking the cdda elements" ) );
}
gst_object_unref( fake );
}
else
{
guLogError( wxT( "Error creating the AcousticId sink" ) );
}
}
}
gst_object_unref( src );
}
else
{
guLogMessage( wxT( "Could not create the gstreamer element for cdda." ) );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
guAudioCdReadTocThread::ExitCode guAudioCdReadTocThread::Entry()
{
if( BuildPipeline() )
{
gst_element_set_state( m_Pipeline, GST_STATE_PLAYING );
m_Running = true;
while( !TestDestroy() && m_Running )
{
Sleep( 1000 );
//gint64 Pos = -1;
//gst_element_query_position( m_Pipeline, GST_FORMAT_TIME, &Pos );
//guLogMessage( wxT( "Running...%llu" ), Pos );
}
//guLogMessage( wxT( "Finished guAcousticIdThread..." ) );
}
return 0;
}
// -------------------------------------------------------------------------------- //
void guAudioCdReadTocThread::SetMbDiscId( const wxString &mbdiscid )
{
m_MBDiscId = wxString( mbdiscid );
guLogMessage( wxT( "The MB DiskId is %s" ), m_MBDiscId.c_str() );
guMusicBrainz MusicBrainz;
guMBReleaseArray MBReleases;
int TrackCount = m_CdTracks.Count();
//guLogMessage( wxT( "There was %i tracks..." ), TrackCount );
if( TrackCount && ( MusicBrainz.GetDiscIdReleases( m_MBDiscId, &MBReleases ) > 0 ) )
{
// MusicBrainz is very strict with request rate... wait 1 second
wxSleep( 1 );
// Get the release track list
int ReleaseCount = MBReleases.GetCount();
//guLogMessage( wxT( "Got %i releases"), ReleaseCount );
for( int ReleaseIndex = 0; ReleaseIndex < ReleaseCount; ReleaseIndex++ )
{
MusicBrainz.GetRecordings( MBReleases[ ReleaseIndex ] );
wxSleep( 1 );
//guLogMessage( wxT( "Got %li tracks in this release..." ), MBReleases[ ReleaseIndex ].m_Recordings.Count() );
}
for( int ReleaseIndex = 0; ReleaseIndex < ReleaseCount; ReleaseIndex++ )
{
guMBRelease & MBRelease = MBReleases[ ReleaseIndex ];
if( TrackCount == ( int ) MBRelease.m_Recordings.Count() )
{
for( int TrackIndex = 0; TrackIndex < TrackCount; TrackIndex++ )
{
guTrack & Track = m_CdTracks[ TrackIndex ];
Track.m_SongName = MBRelease.m_Recordings[ TrackIndex ].m_Title;
Track.m_AlbumArtist = MBRelease.m_ArtistName;
Track.m_ArtistName = MBRelease.m_Recordings[ TrackIndex ].m_ArtistName;
if( Track.m_ArtistName.IsEmpty() )
Track.m_ArtistName = Track.m_AlbumArtist;
Track.m_AlbumName = MBRelease.m_Title;
Track.m_Year = MBRelease.m_Year;
Track.m_Format = wxT( "cdda" );
}
}
}
}
Stop();
}
// -------------------------------------------------------------------------------- //
void guAudioCdReadTocThread::Stop( void )
{
m_Running = false;
}
// -------------------------------------------------------------------------------- //
guCdTracksListBox::guCdTracksListBox( wxWindow * parent ) :
guListView( parent, wxLB_MULTIPLE|guLISTVIEW_COLUMN_SELECT|
guLISTVIEW_COLUMN_SORTING|guLISTVIEW_COLUMN_CLICK_EVENTS|
guLISTVIEW_ALLOWDRAG )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_LastColumnRightClicked = wxNOT_FOUND;
m_LastRowRightClicked = wxNOT_FOUND;
m_ColumnNames.Add( wxT( "#" ) );
m_ColumnNames.Add( _( "Title" ) );
m_ColumnNames.Add( _( "Artist" ) );
m_ColumnNames.Add( _( "Album Artist" ) );
m_ColumnNames.Add( _( "Album" ) );
m_ColumnNames.Add( _( "Genre" ) );
m_ColumnNames.Add( _( "Composer" ) );
m_ColumnNames.Add( _( "Disk" ) );
m_ColumnNames.Add( _( "Length" ) );
m_ColumnNames.Add( _( "Year" ) );
m_Order = Config->ReadNum( CONFIG_KEY_AUDIOCD_ORDER, 0, CONFIG_PATH_AUDIOCD );
m_OrderDesc = Config->ReadNum( CONFIG_KEY_AUDIOCD_ORDERDESC, false, CONFIG_PATH_AUDIOCD );
int ColId;
wxString ColName;
int Count = m_ColumnNames.Count();
for( int Index = 0; Index < Count; Index++ )
{
ColId = Config->ReadNum( wxString::Format( wxT( "id%u" ), Index ), Index, wxT( "audiocd/columns/ids" ) );
ColName = m_ColumnNames[ ColId ];
ColName += ( ( ColId == m_Order ) ? ( m_OrderDesc ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString );
guListViewColumn * Column = new guListViewColumn(
ColName,
ColId,
Config->ReadNum( wxString::Format( wxT( "width%u" ), Index ), 80, wxT( "audiocd/columns/widths" ) ),
Config->ReadBool( wxString::Format( wxT( "show%u" ), Index ), true, wxT( "audiocd/columns/shows" ) )
);
InsertColumn( Column );
}
Bind( guConfigUpdatedEvent, &guCdTracksListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( guEVT_LISTBOX_ITEM_COL_RCLICKED, &guCdTracksListBox::OnItemColumnRClicked, this );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guCdTracksListBox::~guCdTracksListBox()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
int Count = m_ColumnNames.Count();
for( int Index = 0; Index < Count; Index++ )
{
Config->WriteNum( wxString::Format( wxT( "id%u" ), Index ),
( * m_Columns )[ Index ].m_Id, wxT( "audiocd/columns/ids" ) );
Config->WriteNum( wxString::Format( wxT( "width%u" ), Index ),
( * m_Columns )[ Index ].m_Width, wxT( "audiocd/columns/widths" ) );
Config->WriteBool( wxString::Format( wxT( "show%u" ), Index ),
( * m_Columns )[ Index ].m_Enabled, wxT( "audiocd/columns/shows" ) );
}
Config->WriteNum( CONFIG_KEY_AUDIOCD_ORDER, m_Order, CONFIG_PATH_AUDIOCD );
Config->WriteBool( CONFIG_KEY_AUDIOCD_ORDERDESC, m_OrderDesc, CONFIG_PATH_AUDIOCD );
Unbind( guConfigUpdatedEvent, &guCdTracksListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( guEVT_LISTBOX_ITEM_COL_RCLICKED, &guCdTracksListBox::OnItemColumnRClicked, this );
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_AUDIOCD_ITEM_PLAY );
RealAccelCmds.Add( ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_AUDIOCD_ITEM_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ARTIST );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
wxString guCdTracksListBox::OnGetItemText( const int row, const int col ) const
{
guTrack * Track;
//guLogMessage( wxT( "GetItemText( %i, %i ) %i-%i %i" ), row, col, m_ItemsFirst, m_ItemsLast, m_Items.Count() );
Track = &m_AudioCdTracks[ row ];
switch( ( * m_Columns )[ col ].m_Id )
{
case guAUDIOCD_COLUMN_NUMBER :
if( Track->m_Number )
return wxString::Format( wxT( "%u" ), Track->m_Number );
else
return wxEmptyString;
case guAUDIOCD_COLUMN_TITLE :
return Track->m_SongName;
case guAUDIOCD_COLUMN_ARTIST :
return Track->m_ArtistName;
case guAUDIOCD_COLUMN_ALBUMARTIST :
return Track->m_AlbumArtist;
case guAUDIOCD_COLUMN_ALBUM :
return Track->m_AlbumName;
case guAUDIOCD_COLUMN_GENRE :
return Track->m_GenreName;
case guAUDIOCD_COLUMN_COMPOSER :
return Track->m_Composer;
case guAUDIOCD_COLUMN_DISK :
return Track->m_Disk;
case guAUDIOCD_COLUMN_LENGTH :
return LenToString( Track->m_Length );
case guAUDIOCD_COLUMN_YEAR :
if( Track->m_Year )
return wxString::Format( wxT( "%u" ), Track->m_Year );
else
return wxEmptyString;
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::GetItemsList( void )
{
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::SetTrackList( guTrackArray &audiocdtracks )
{
m_AudioCdTracks.Clear();
int Count = audiocdtracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_AudioCdTracks.Add( new guTrack( audiocdtracks[ Index ] ) );
}
ReloadItems( true );
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::ClearTracks( void )
{
m_AudioCdTracks.Clear();
ReloadItems( true );
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::UpdatedTracks( guTrackArray * tracks )
{
int ItemCount = m_AudioCdTracks.Count();
if( !ItemCount )
return;
int TrackCount = tracks->Count();
for( int TrackIndex = 0; TrackIndex < TrackCount; TrackIndex++ )
{
guTrack &CurTrack = tracks->Item( TrackIndex );
for( int ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
if( ( CurTrack.m_SongId == m_AudioCdTracks[ ItemIndex ].m_SongId ) )
{
m_AudioCdTracks[ ItemIndex ] = CurTrack;
RefreshRow( ItemIndex );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::ReloadItems( bool reset )
{
//
wxArrayInt Selection;
int FirstVisible = 0;
if( reset )
{
SetSelection( -1 );
}
else
{
Selection = GetSelectedItems( false );
FirstVisible = GetVisibleRowsBegin();
}
//m_AudioCdTracks.Empty();
GetItemsList();
SetItemCount( m_AudioCdTracks.Count() );
if( !reset )
{
SetSelectedItems( Selection );
ScrollToRow( FirstVisible );
}
RefreshAll();
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::OnItemColumnRClicked( wxListEvent &event )
{
m_LastColumnRightClicked = event.m_col;
m_LastRowRightClicked = event.GetInt();
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::AppendFastEditMenu( wxMenu * menu, const int selcount ) const
{
wxMenuItem * MenuItem;
//guLogMessage( wxT( "guCdTracksListBox::AppendFastEditMenu %i - %i" ), m_LastColumnRightClicked, m_LastRowRightClicked );
if( m_LastColumnRightClicked == wxNOT_FOUND || ( m_LastColumnRightClicked >= ( int ) m_Columns->Count() ) )
{
return;
}
int ColumnId = GetColumnId( m_LastColumnRightClicked );
// If its a column not editable
if( ColumnId == guAUDIOCD_COLUMN_NUMBER ||
ColumnId == guAUDIOCD_COLUMN_LENGTH )
return;
menu->AppendSeparator();
wxString MenuText = _( "Edit" );
MenuText += wxT( " " ) + m_ColumnNames[ ColumnId ];
MenuItem = new wxMenuItem( menu, ID_AUDIOCD_EDIT_COLUMN, MenuText, _( "Edit the clicked column for the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
menu->Append( MenuItem );
if( selcount > 1 )
{
MenuText = _( "Set" );
MenuText += wxT( " " ) + m_ColumnNames[ ColumnId ] + wxT( " " );
MenuText += _( "to" );
wxString ItemText = OnGetItemText( m_LastRowRightClicked, m_LastColumnRightClicked );
ItemText.Replace( wxT( "&" ), wxT( "&&" ) );
MenuText += wxT( " '" ) + ItemText + wxT( "'" );
MenuItem = new wxMenuItem( menu, ID_AUDIOCD_SET_COLUMN, MenuText, _( "Set the clicked column for the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
menu->Append( MenuItem );
}
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::CreateContextMenu( wxMenu * Menu ) const
{
int SelCount = GetSelectedCount();
if( SelCount )
{
wxMenuItem * MenuItem;
MenuItem = new wxMenuItem( Menu, ID_AUDIOCD_ITEM_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected songs to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_AUDIOCD_REFRESH_METADATA,
_( "Search again" ),
_( "Search again for cd metadata" ) );
Menu->Append( MenuItem );
AppendFastEditMenu( Menu, SelCount );
Menu->AppendSeparator();
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
MainFrame->CreateCopyToMenu( Menu );
}
else
{
wxMenuItem * MenuItem;
MenuItem = new wxMenuItem( Menu, wxID_ANY, _( "No selected items..." ), _( "Copy the current selected tracks to a directory or device" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_status_error ) );
Menu->Append( MenuItem );
}
}
// -------------------------------------------------------------------------------- //
int inline guCdTracksListBox::GetItemId( const int row ) const
{
return m_AudioCdTracks[ row ].m_SongId;
}
// -------------------------------------------------------------------------------- //
wxString inline guCdTracksListBox::GetItemName( const int row ) const
{
return m_AudioCdTracks[ row ].m_SongName;
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::SetOrder( int columnid )
{
if( m_Order != columnid )
{
m_Order = columnid;
m_OrderDesc = ( columnid != 0 );
}
else
m_OrderDesc = !m_OrderDesc;
int CurColId;
int count = m_ColumnNames.Count();
for( int Index = 0; Index < count; Index++ )
{
CurColId = GetColumnId( Index );
SetColumnLabel( Index,
m_ColumnNames[ CurColId ] + ( ( CurColId == m_Order ) ?
( m_OrderDesc ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
}
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::GetAllSongs( guTrackArray * tracks )
{
int Count = GetItemCount();
for( int Index = 0; Index < Count; Index++ )
{
tracks->Add( new guTrack( m_AudioCdTracks[ Index ] ) );
}
}
// -------------------------------------------------------------------------------- //
int guCdTracksListBox::GetSelectedSongs( guTrackArray * tracks, const bool isdrag ) const
{
unsigned long cookie;
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
tracks->Add( new guTrack( m_AudioCdTracks[ item ] ) );
item = GetNextSelected( cookie );
}
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
wxVariant guCdTracksListBox::GetLastDataClicked( void )
{
guTrack * Track = &m_AudioCdTracks[ m_LastRowRightClicked ];
int ColId = GetColumnId( m_LastColumnRightClicked );
switch( ColId )
{
case guSONGS_COLUMN_TITLE :
return wxVariant( Track->m_SongName );
case guSONGS_COLUMN_ARTIST :
return wxVariant( Track->m_ArtistName );
case guSONGS_COLUMN_ALBUMARTIST :
return wxVariant( Track->m_AlbumArtist );
case guSONGS_COLUMN_ALBUM :
return wxVariant( Track->m_AlbumName );
case guSONGS_COLUMN_GENRE :
return wxVariant( Track->m_GenreName );
case guSONGS_COLUMN_COMPOSER :
return wxVariant( Track->m_Composer );
case guSONGS_COLUMN_DISK :
return wxVariant( Track->m_Disk );
case guSONGS_COLUMN_YEAR :
return wxVariant( ( long ) Track->m_Year );
}
return wxVariant();
}
// -------------------------------------------------------------------------------- //
void guCdTracksListBox::GetCounters( wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
int Count = m_AudioCdTracks.Count();
* count = Count;
* len = 0;
* size = 0;
for( int Index = 0; Index < Count; Index++ )
{
* len += m_AudioCdTracks[ Index ].m_Length;
}
}
// -------------------------------------------------------------------------------- //
guAudioCdPanel::guAudioCdPanel( wxWindow * parent, guPlayerPanel * playerpanel ) :
wxPanel( parent )
{
m_PlayerPanel = playerpanel;
wxBoxSizer * MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
m_CdTracksListBox = new guCdTracksListBox( this );
MainSizer->Add( m_CdTracksListBox, 1, wxEXPAND, 5 );
SetSizer( MainSizer );
Layout();
Bind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackPlay, this, ID_AUDIOCD_ITEM_PLAY );
Bind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackEnqueue, this, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALL, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ARTIST );
m_CdTracksListBox->Bind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackCopyTo, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
m_CdTracksListBox->Bind( wxEVT_LISTBOX_DCLICK, &guAudioCdPanel::OnAudioCdTrackActivated, this );
//Bind( guConfigUpdatedEvent, &guAudioCdPanel::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdRefresh, this, ID_AUDIOCD_REFRESH_METADATA );
Bind( wxEVT_MENU, &guAudioCdPanel::OnSongSetField, this, ID_AUDIOCD_SET_COLUMN );
Bind( wxEVT_MENU, &guAudioCdPanel::OnSongEditField, this, ID_AUDIOCD_EDIT_COLUMN );
guAudioCdReadTocThread * AudioCdReadTocThread = new guAudioCdReadTocThread( this );
if( !AudioCdReadTocThread )
{
guLogMessage( wxT( "Could not create the audio cd read toc thread" ) );
}
}
// -------------------------------------------------------------------------------- //
guAudioCdPanel::~guAudioCdPanel()
{
Unbind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackPlay, this, ID_AUDIOCD_ITEM_PLAY );
Unbind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackEnqueue, this, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALL, ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ARTIST );
m_CdTracksListBox->Unbind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdTrackCopyTo, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
m_CdTracksListBox->Unbind( wxEVT_LISTBOX_DCLICK, &guAudioCdPanel::OnAudioCdTrackActivated, this );
//Unbind( guConfigUpdatedEvent, &guAudioCdPanel::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guAudioCdPanel::OnAudioCdRefresh, this, ID_AUDIOCD_REFRESH_METADATA );
Unbind( wxEVT_MENU, &guAudioCdPanel::OnSongSetField, this, ID_AUDIOCD_SET_COLUMN );
Unbind( wxEVT_MENU, &guAudioCdPanel::OnSongEditField, this, ID_AUDIOCD_EDIT_COLUMN );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::GetCounters( wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
m_CdTracksListBox->GetCounters( count, len, size );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::SetAudioCdTracks( guTrackArray &audiocdtracks )
{
m_CdTracksListBox->SetTrackList( audiocdtracks );
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::UpdateVolume( const bool added )
{
guLogMessage( wxT( "The audio cd volume changed " ) );
if( added )
{
guAudioCdReadTocThread * AudioCdReadTocThread = new guAudioCdReadTocThread( this );
if( !AudioCdReadTocThread )
{
guLogMessage( wxT( "Could not create the audio cd read toc thread" ) );
}
}
else
{
m_CdTracksListBox->ClearTracks();
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnSelectAudioCdTracks( const bool enqueue, const int aftercurrent )
{
guTrackArray Tracks;
m_CdTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
{
m_CdTracksListBox->GetAllSongs( &Tracks );
}
if( Tracks.Count() )
{
if( enqueue )
{
m_PlayerPanel->AddToPlayList( Tracks, true, aftercurrent );
}
else
{
m_PlayerPanel->SetPlayList( Tracks );
}
}
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnAudioCdTrackPlay( wxCommandEvent &event )
{
OnSelectAudioCdTracks( false );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnAudioCdTrackEnqueue( wxCommandEvent &event )
{
OnSelectAudioCdTracks( true, event.GetId() - ID_AUDIOCD_ITEM_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnAudioCdTrackCopyTo( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_CdTracksListBox->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnAudioCdTrackActivated( wxCommandEvent &event )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
OnSelectAudioCdTracks( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnAudioCdRefresh( wxCommandEvent &event )
{
UpdateVolume( true );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnSongSetField( wxCommandEvent &event )
{
int ColumnId = m_CdTracksListBox->GetColumnId( m_CdTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_CdTracksListBox->GetSelectedSongs( &Tracks );
wxVariant NewData = m_CdTracksListBox->GetLastDataClicked();
//guLogMessage( wxT( "Setting Data to : %s" ), NewData.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = NewData.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = NewData.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = NewData.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = NewData.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = NewData.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = NewData.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = NewData.GetLong();
break;
}
}
m_CdTracksListBox->UpdatedTracks( &Tracks );
}
// -------------------------------------------------------------------------------- //
void guAudioCdPanel::OnSongEditField( wxCommandEvent &event )
{
int ColumnId = m_CdTracksListBox->GetColumnId( m_CdTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_CdTracksListBox->GetSelectedSongs( &Tracks );
wxString Label = m_CdTracksListBox->GetColumnNames()[ ColumnId ];
wxVariant DefValue = m_CdTracksListBox->GetLastDataClicked();
wxArrayString Items;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxVariant Value;
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_TITLE :
Value = Track->m_SongName;
break;
case guSONGS_COLUMN_ARTIST :
Value = Track->m_ArtistName;
break;
case guSONGS_COLUMN_ALBUMARTIST :
Value = Track->m_AlbumArtist;
break;
case guSONGS_COLUMN_ALBUM :
Value = Track->m_AlbumName;
break;
case guSONGS_COLUMN_GENRE :
Value = Track->m_GenreName;
break;
case guSONGS_COLUMN_COMPOSER :
Value = Track->m_Composer;
break;
case guSONGS_COLUMN_DISK :
Value = Track->m_Disk;
break;
case guSONGS_COLUMN_YEAR :
Value = ( long ) Track->m_Year;
break;
}
if( Items.Index( Value.GetString() ) == wxNOT_FOUND )
Items.Add( Value.GetString() );
}
guEditWithOptions * FieldEditor = new guEditWithOptions( this, _( "Field Editor" ), Label, DefValue.GetString(), Items );
if( FieldEditor )
{
if( FieldEditor->ShowModal() == wxID_OK )
{
DefValue = FieldEditor->GetData();
//guLogMessage( wxT( "Setting Data to : %s" ), DefValue.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_TITLE :
Track->m_SongName = DefValue.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = DefValue.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = DefValue.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = DefValue.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = DefValue.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = DefValue.GetLong();
break;
}
}
m_CdTracksListBox->UpdatedTracks( &Tracks );
}
FieldEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
| 39,397
|
C++
|
.cpp
| 943
| 33.565217
| 147
| 0.541384
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,601
|
AlbumBrowser.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/albumbrowser/AlbumBrowser.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AlbumBrowser.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "CoverEdit.h"
#include "Images.h"
#include "LabelEditor.h"
#include "LibPanel.h"
#include "LibUpdate.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "OnlineLinks.h"
#include "PlayListAppend.h"
#include "SelCoverFile.h"
#include "Settings.h"
#include "StaticBitmap.h"
#include "ShowImage.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include "wx/clipbrd.h"
#include <wx/dnd.h>
#include <wx/menu.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guAlbumBrowserItemArray )
#define guALBUMBROWSER_REFRESH_DELAY 60
#define guALBUMBROWSER_GRID_SIZE_WIDTH 140
//#define guALBUMBROWSER_GRID_SIZE_HEIGHT 180
static int guALBUMBROWSER_GRID_SIZE_HEIGHT = -1;
#define guALBUMBROWSER_TIMER_ID_REFRESH 3
#define guALBUMBROWSER_TIMER_ID_BITMAP_CLICKED 4
void AddAlbumCommands( wxMenu * Menu, int SelCount );
// -------------------------------------------------------------------------------- //
class guUpdateAlbumDetails : public wxThread
{
protected :
guAlbumBrowser * m_AlbumBrowser;
public :
guUpdateAlbumDetails( guAlbumBrowser * albumbrowser );
~guUpdateAlbumDetails();
virtual ExitCode Entry();
};
// -------------------------------------------------------------------------------- //
guUpdateAlbumDetails::guUpdateAlbumDetails( guAlbumBrowser * albumbrowser )
{
m_AlbumBrowser = albumbrowser;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY );
Run();
}
}
// -------------------------------------------------------------------------------- //
guUpdateAlbumDetails::~guUpdateAlbumDetails()
{
if( !TestDestroy() )
{
m_AlbumBrowser->ClearUpdateDetailsThread();
}
}
// -------------------------------------------------------------------------------- //
guUpdateAlbumDetails::ExitCode guUpdateAlbumDetails::Entry()
{
if( !TestDestroy() )
{
//guLogMessage( wxT( "Searching details..." ) );
guDbLibrary * Db = m_AlbumBrowser->m_Db;
m_AlbumBrowser->m_AlbumItemsMutex.Lock();
int Count = m_AlbumBrowser->m_AlbumItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
if( TestDestroy() )
break;
if( m_AlbumBrowser->m_AlbumItems[ Index ].m_AlbumId != ( unsigned int ) wxNOT_FOUND )
{
Db->GetAlbumDetails( m_AlbumBrowser->m_AlbumItems[ Index ].m_AlbumId,
( int * ) &m_AlbumBrowser->m_AlbumItems[ Index ].m_Year,
( int * ) &m_AlbumBrowser->m_AlbumItems[ Index ].m_TrackCount );
if( TestDestroy() )
break;
}
}
if( !TestDestroy() )
{
wxCommandEvent event( wxEVT_MENU, ID_ALBUMBROWSER_UPDATEDETAILS );
//event.SetInt( Index );
wxPostEvent( m_AlbumBrowser, event );
//guLogMessage( wxT( "Sent Details %i %i for %i" ), m_AlbumBrowser->m_AlbumItems[ Index ].m_Year, m_AlbumBrowser->m_AlbumItems[ Index ].m_TrackCount, Index );
}
}
m_AlbumBrowser->m_AlbumItemsMutex.Unlock();
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guAlbumBrowserItemPanel
// -------------------------------------------------------------------------------- //
guAlbumBrowserItemPanel::guAlbumBrowserItemPanel( wxWindow * parent, const int index,
guAlbumBrowserItem * albumitem ) : wxPanel( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS )
{
m_AlbumBrowserItem = albumitem;
m_AlbumBrowser = ( guAlbumBrowser * ) parent;
wxFont CurrentFont = GetFont();
// GUI
m_MainSizer = new wxBoxSizer( wxVERTICAL );
m_Bitmap = new wxStaticBitmap( this, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize( GUCOVER_IMAGE_SIZE, GUCOVER_IMAGE_SIZE ) );
m_MainSizer->Add( m_Bitmap, 0, wxRIGHT, 2 );
m_AlbumLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 100, 16 ) );
CurrentFont.SetWeight( wxFONTWEIGHT_BOLD );
CurrentFont.SetPointSize( CurrentFont.GetPointSize() - 1 );
m_AlbumLabel->SetFont( CurrentFont );
m_MainSizer->Add( m_AlbumLabel, 0, wxEXPAND, 5 );
m_ArtistLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 100, 16 ) );
CurrentFont.SetWeight( wxFONTWEIGHT_NORMAL );
m_ArtistLabel->SetFont( CurrentFont );
m_MainSizer->Add( m_ArtistLabel, 0, wxEXPAND, 5 );
m_TracksLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 100, 16 ) );
m_TracksLabel->SetFont( CurrentFont );
m_MainSizer->Add( m_TracksLabel, 0, wxEXPAND, 5 );
SetSizer( m_MainSizer );
Layout();
m_MainSizer->Fit( this );
m_MainSizer->SetSizeHints( this );
SetDropTarget( new guAlbumBrowserDropTarget( m_AlbumBrowser->m_MediaViewer, this ) );
m_BitmapTimer.SetOwner( this );
Bind( wxEVT_CONTEXT_MENU, &guAlbumBrowserItemPanel::OnContextMenu, this, wxID_ANY );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
m_Bitmap->Bind( wxEVT_LEFT_DCLICK, &guAlbumBrowserItemPanel::OnAlbumDClicked, this );
m_Bitmap->Bind( wxEVT_LEFT_DOWN, &guAlbumBrowserItemPanel::OnBitmapClicked, this );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnPlayClicked, this, ID_ALBUMBROWSER_PLAY );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnEnqueueClicked, this, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEditLabelsClicked, this, ID_ALBUMBROWSER_EDITLABELS );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEditTracksClicked, this, ID_ALBUMBROWSER_EDITTRACKS );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCopyToClipboard, this, ID_ALBUMBROWSER_COPYTOCLIPBOARD );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumSelectName, this, ID_ALBUM_SELECTNAME );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnArtistSelectName, this, ID_ARTIST_SELECTNAME );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumDownloadCoverClicked, this, ID_ALBUMBROWSER_SEARCHCOVER );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumSelectCoverClicked, this, ID_ALBUMBROWSER_SELECTCOVER );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumDeleteCoverClicked, this, ID_ALBUMBROWSER_DELETECOVER );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEmbedCoverClicked, this, ID_ALBUMBROWSER_EMBEDCOVER );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
m_Bitmap->Bind( wxEVT_LEFT_DOWN, &guAlbumBrowserItemPanel::OnMouse, this );
m_Bitmap->Bind( wxEVT_LEFT_UP, &guAlbumBrowserItemPanel::OnMouse, this );
m_Bitmap->Bind( wxEVT_MOTION, &guAlbumBrowserItemPanel::OnMouse, this );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnBeginDrag, this, ID_ALBUMBROWSER_BEGINDRAG );
Bind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCoverBeginDrag, this, ID_ALBUMBROWSER_COVER_BEGINDRAG );
Bind( wxEVT_TIMER, &guAlbumBrowserItemPanel::OnTimer, this );
m_Bitmap->Bind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_AlbumLabel->Bind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_ArtistLabel->Bind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_TracksLabel->Bind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
}
// -------------------------------------------------------------------------------- //
guAlbumBrowserItemPanel::~guAlbumBrowserItemPanel()
{
Unbind( wxEVT_CONTEXT_MENU, &guAlbumBrowserItemPanel::OnContextMenu, this, wxID_ANY );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
m_Bitmap->Unbind( wxEVT_LEFT_DCLICK, &guAlbumBrowserItemPanel::OnAlbumDClicked, this );
m_Bitmap->Unbind( wxEVT_LEFT_DOWN, &guAlbumBrowserItemPanel::OnBitmapClicked, this );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnPlayClicked, this, ID_ALBUMBROWSER_PLAY );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnEnqueueClicked, this, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEditLabelsClicked, this, ID_ALBUMBROWSER_EDITLABELS );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEditTracksClicked, this, ID_ALBUMBROWSER_EDITTRACKS );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCopyToClipboard, this, ID_ALBUMBROWSER_COPYTOCLIPBOARD );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumSelectName, this, ID_ALBUM_SELECTNAME );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnArtistSelectName, this, ID_ARTIST_SELECTNAME );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumDownloadCoverClicked, this, ID_ALBUMBROWSER_SEARCHCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumSelectCoverClicked, this, ID_ALBUMBROWSER_SELECTCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumDeleteCoverClicked, this, ID_ALBUMBROWSER_DELETECOVER );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumEmbedCoverClicked, this, ID_ALBUMBROWSER_EMBEDCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnAlbumCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
m_Bitmap->Unbind( wxEVT_LEFT_DOWN, &guAlbumBrowserItemPanel::OnMouse, this );
m_Bitmap->Unbind( wxEVT_LEFT_UP, &guAlbumBrowserItemPanel::OnMouse, this );
m_Bitmap->Unbind( wxEVT_MOTION, &guAlbumBrowserItemPanel::OnMouse, this );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnBeginDrag, this, ID_ALBUMBROWSER_BEGINDRAG );
Unbind( wxEVT_MENU, &guAlbumBrowserItemPanel::OnCoverBeginDrag, this, ID_ALBUMBROWSER_COVER_BEGINDRAG );
Unbind( wxEVT_TIMER, &guAlbumBrowserItemPanel::OnTimer, this );
m_Bitmap->Unbind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_AlbumLabel->Unbind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_ArtistLabel->Unbind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
m_TracksLabel->Unbind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, m_AlbumBrowser );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::SetAlbumItem( const int index, guAlbumBrowserItem * albumitem, wxBitmap * blankcd )
{
m_Index = index;
m_AlbumBrowserItem = albumitem;
if( m_AlbumBrowserItem )
{
m_Bitmap->Show();
//guLogMessage( wxT( "Inserting item %i '%s'" ), index, albumitem->m_AlbumName.c_str() );
if( m_AlbumBrowserItem->m_CoverBitmap )
m_Bitmap->SetBitmap( * m_AlbumBrowserItem->m_CoverBitmap );
else
m_Bitmap->SetBitmap( * blankcd );
m_ArtistLabel->SetLabel( m_AlbumBrowserItem->m_ArtistName );
m_ArtistLabel->SetToolTip( m_AlbumBrowserItem->m_ArtistName );
m_AlbumLabel->SetLabel( m_AlbumBrowserItem->m_AlbumName );
m_AlbumLabel->SetToolTip( m_AlbumBrowserItem->m_AlbumName );
}
else
{
//m_Bitmap->SetBitmap( * blankcd );
m_Bitmap->Hide();
m_ArtistLabel->SetLabel( wxEmptyString );
m_AlbumLabel->SetLabel( wxEmptyString );
m_TracksLabel->SetLabel( wxEmptyString );
m_ArtistLabel->SetToolTip( wxEmptyString );
m_AlbumLabel->SetToolTip( wxEmptyString );
m_TracksLabel->SetToolTip( wxEmptyString );
}
//Layout();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::UpdateDetails( void )
{
if( m_AlbumBrowserItem )
{
wxString Label;
if( m_AlbumBrowserItem->m_Year )
{
Label += wxString::Format( wxT( "(%u) " ), m_AlbumBrowserItem->m_Year );
}
Label += wxString::Format( wxT( "%u " ), m_AlbumBrowserItem->m_TrackCount ) + _( "Tracks" );
m_TracksLabel->SetLabel( Label );
m_TracksLabel->SetToolTip( Label );
//m_MainSizer->Layout();
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnContextMenu( wxContextMenuEvent &event )
{
m_AlbumBrowser->SetLastAlbumItem( m_AlbumBrowserItem );
if( !m_AlbumBrowserItem )
return;
//m_Bitmap->StopTimer();
wxMenu Menu;
wxMenuItem * MenuItem;
wxPoint Point = event.GetPosition();
// If from keyboard
if( Point.x == -1 && Point.y == -1 )
{
wxSize Size = GetSize();
Point.x = Size.x / 2;
Point.y = Size.y / 2;
}
else
{
Point = ScreenToClient( Point );
}
if( m_AlbumBrowserItem->m_AlbumId != ( unsigned int ) wxNOT_FOUND )
{
int ContextMenuFlags = m_AlbumBrowser->GetContextMenuFlags();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_PLAY, _( "Play" ), _( "Play the album tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, _( "Enqueue" ), _( "Enqueue the album tracks to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu.Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu.Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EDITLABELS, _( "Edit Labels" ), _( "Edit the labels assigned to the selected albums" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu.Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EDITTRACKS, _( "Edit Songs" ), _( "Edit the selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUM_SELECTNAME, _( "Search Album" ), _( "Search the album in the library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_search ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ARTIST_SELECTNAME, _( "Search Artist" ), _( "Search the artist in the library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_search ) );
Menu.Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_DOWNLOAD_COVERS )
{
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_SEARCHCOVER, _( "Download Cover" ), _( "Download cover for the current selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_SELECTCOVER, _( "Select Cover" ), _( "Select the cover image file from disk" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_DELETECOVER, _( "Delete Cover" ), _( "Delete the cover for the selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_delete ) );
Menu.Append( MenuItem );
}
if( ContextMenuFlags & guCONTEXTMENU_EMBED_COVERS )
{
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EMBEDCOVER, _( "Embed Cover" ), _( "Embed the cover to the selected album tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
wxMenu * SortMenu = new wxMenu();
int SortSelected = m_AlbumBrowser->GetSortSelected();
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_NAME, _( "Name" ), _( "Sort albums by name" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_NAME );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_YEAR, _( "Year" ), _( "Sort albums by year" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_YEAR );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_YEAR_REVERSE, _( "Year Descending" ), _( "Sort albums by year descendant" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_YEAR_REVERSE );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_ARTIST, _( "Artist Name" ), _( "Sort albums by artist name" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_ARTIST_NAME );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_ARTIST_YEAR, _( "Artist, Year" ), _( "Sort albums by artist, year" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_ARTIST_YEAR );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_ARTIST_YEAR_REVERSE, _( "Artist, Year Descending" ), _( "Sort albums by artist, year descendant" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_ARTIST_YEAR_REVERSE );
MenuItem = new wxMenuItem( SortMenu, ID_ALBUMBROWSER_ORDER_ADDEDTIME, _( "Added" ), _( "Sort albums by year descendant" ), wxITEM_CHECK );
SortMenu->Append( MenuItem );
MenuItem->Check( SortSelected == guALBUMS_ORDER_ADDEDTIME );
Menu.AppendSubMenu( SortMenu, _( "Sort By" ), _( "Set the albums sorting" ) );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_COPYTOCLIPBOARD, _( "Copy to Clipboard" ), _( "Copy the album info to clipboard" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_copy ) );
Menu.Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu.AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
MainFrame->CreateCopyToMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_LINKS )
{
AddOnlineLinksMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
{
AddAlbumCommands( &Menu, 1 );
}
}
m_AlbumBrowser->CreateContextMenu( &Menu );
}
// Add Links and Commands
PopupMenu( &Menu, Point.x, Point.y );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnCommandClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnCommandClicked( event.GetId(), m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnSearchLinkClicked( wxCommandEvent &event )
{
ExecuteOnlineLink( event.GetId(), m_AlbumBrowserItem->m_ArtistName + wxT( " " ) +
m_AlbumBrowserItem->m_AlbumName );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnPlayClicked( wxCommandEvent &event )
{
m_AlbumBrowser->SelectAlbum( m_AlbumBrowserItem->m_AlbumId, false );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnEnqueueClicked( wxCommandEvent &event )
{
m_AlbumBrowser->SelectAlbum( m_AlbumBrowserItem->m_AlbumId, true, event.GetId() - ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnCopyToClipboard( wxCommandEvent &event )
{
wxTheClipboard->UsePrimarySelection( false );
if( wxTheClipboard->Open() )
{
wxTheClipboard->Clear();
if( !wxTheClipboard->AddData( new wxTextDataObject(
m_AlbumBrowserItem->m_ArtistName + wxT( " " ) + m_AlbumBrowserItem->m_AlbumName ) ) )
{
guLogError( wxT( "Can't copy data to the clipboard" ) );
}
wxTheClipboard->Close();
}
else
{
guLogError( wxT( "Could not open the clipboard object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumSelectName( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumSelectName( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnArtistSelectName( wxCommandEvent &event )
{
m_AlbumBrowser->OnArtistSelectName( m_AlbumBrowserItem->m_ArtistId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumDownloadCoverClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumDownloadCoverClicked( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumSelectCoverClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumSelectCoverClicked( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumDeleteCoverClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumDeleteCoverClicked( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumEmbedCoverClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumEmbedCoverClicked( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumCopyToClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumCopyToClicked( m_AlbumBrowserItem->m_AlbumId, event.GetId() );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumEditLabelsClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumEditLabelsClicked( m_AlbumBrowserItem );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumEditTracksClicked( wxCommandEvent &event )
{
m_AlbumBrowser->OnAlbumEditTracksClicked( m_AlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnMouse( wxMouseEvent &event )
{
if( event.Dragging() )
{
//guLogMessage( wxT( "OnMouse...%i %i %i" ), m_DragCount, event.Dragging(), event.ControlDown() );
if( !m_DragCount )
{
m_DragStart = event.GetPosition();
}
if( ++m_DragCount == 3 )
{
if( m_BitmapTimer.IsRunning() )
m_BitmapTimer.Stop();
wxCommandEvent DragEvent( wxEVT_MENU, ID_ALBUMBROWSER_BEGINDRAG );
if( event.ControlDown() )
{
DragEvent.SetId( ID_ALBUMBROWSER_COVER_BEGINDRAG );
}
DragEvent.SetEventObject( this );
//DragEvent.SetInt( m_AlbumBrowserItem->m_CoverId );
GetEventHandler()->ProcessEvent( DragEvent );
}
return;
}
else
{
m_DragCount = 0;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
int guAlbumBrowserItemPanel::GetDragFiles( guDataObjectComposite * files )
{
guTrackArray Tracks;
wxArrayString Filenames;
int Count = m_AlbumBrowser->GetAlbumTracks( m_AlbumBrowserItem->m_AlbumId, &Tracks );
for( int Index = 0; Index < Count; Index++ )
{
if( Tracks[ Index ].m_Offset )
continue;
Filenames.Add( guFileDnDEncode( Tracks[ Index ].m_FileName ) );
}
files->SetTracks( Tracks );
files->SetFiles( Filenames );
return Count;
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnBeginDrag( wxCommandEvent &event )
{
if( !m_AlbumBrowserItem )
return;
guDataObjectComposite Files;
if( GetDragFiles( &Files ) )
{
wxDropSource source( Files, this );
wxDragResult Result = source.DoDragDrop();
if( Result )
{
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnCoverBeginDrag( wxCommandEvent &event )
{
if( !m_AlbumBrowserItem )
return;
//guLogMessage( wxT( "On BeginDrag event..." ) );
wxFileDataObject Files;
wxString CoverFile = m_AlbumBrowser->GetAlbumCoverFile( m_AlbumBrowserItem->m_CoverId );
if( !CoverFile.IsEmpty() )
{
Files.AddFile( CoverFile );
wxDropSource source( Files, this );
wxDragResult Result = source.DoDragDrop( wxDrag_CopyOnly );
if( Result )
{
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::SetAlbumCover( const wxString &cover )
{
if( m_AlbumBrowserItem )
m_AlbumBrowser->SetAlbumCover( m_AlbumBrowserItem->m_AlbumId, cover );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnAlbumDClicked( wxMouseEvent &event )
{
if( m_BitmapTimer.IsRunning() )
m_BitmapTimer.Stop();
if( m_AlbumBrowserItem )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_AlbumBrowser->SelectAlbum( m_AlbumBrowserItem->m_AlbumId,
Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false , CONFIG_PATH_GENERAL ) );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnBitmapClicked( wxMouseEvent &event )
{
if( m_BitmapTimer.IsRunning() )
m_BitmapTimer.Stop();
m_BitmapTimer.Start( 300, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowserItemPanel::OnTimer( wxTimerEvent &event )
{
if( m_AlbumBrowserItem )
m_AlbumBrowser->OnBitmapClicked( m_AlbumBrowserItem, ClientToScreen( m_Bitmap->GetPosition() ) );
}
// -------------------------------------------------------------------------------- //
// guAlbumBrowser
// -------------------------------------------------------------------------------- //
guAlbumBrowser::guAlbumBrowser( wxWindow * parent, guMediaViewer * mediaviewer ) :
wxPanel( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxWANTS_CHARS ),
m_RefreshTimer( this, guALBUMBROWSER_TIMER_ID_REFRESH ),
m_BitmapClickTimer( this, guALBUMBROWSER_TIMER_ID_BITMAP_CLICKED )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_PlayerPanel = mediaviewer->GetPlayerPanel();
m_UpdateDetails = NULL;
m_ItemStart = 0;
m_LastItemStart = wxNOT_FOUND;
m_ItemCount = 1;
m_BlankCD = new wxBitmap( guImage( guIMAGE_INDEX_no_cover ) );
m_ConfigPath = mediaviewer->ConfigPath() + wxT( "/albumbrowser" );
m_BigCoverShowed = false;
m_BigCoverTracksContextMenu = false;
m_DragCount = 0;
m_MouseWasLeftUp = false;
m_MouseSelecting = false;
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
if( guALBUMBROWSER_GRID_SIZE_HEIGHT == -1 )
{
CalculateMaxItemHeight();
}
CreateControls();
CreateAcceleratorTable();
RefreshCount();
}
// -------------------------------------------------------------------------------- //
guAlbumBrowser::~guAlbumBrowser()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteNum( wxT( "Sort" ), m_SortSelected, m_ConfigPath );
if( m_BlankCD )
delete m_BlankCD;
Unbind( wxEVT_SIZE, &guAlbumBrowser::OnChangedSize, this );
Unbind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, this );
m_NavSlider->Unbind( wxEVT_SCROLL_CHANGED, &guAlbumBrowser::OnChangingPosition, this );
m_NavSlider->Unbind( wxEVT_SCROLL_THUMBTRACK, &guAlbumBrowser::OnChangingPosition, this );
Unbind( wxEVT_TIMER, &guAlbumBrowser::OnRefreshTimer, this, guALBUMBROWSER_TIMER_ID_REFRESH );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnUpdateDetails, this, ID_ALBUMBROWSER_UPDATEDETAILS );
Unbind( wxEVT_MOUSEWHEEL, &guAlbumBrowser::OnMouseWheel, this );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnGoToSearch, this, ID_ALBUMBROWSER_SEARCH );
Unbind( guConfigUpdatedEvent, &guAlbumBrowser::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnSortSelected, this, ID_ALBUMBROWSER_ORDER_NAME, ID_ALBUMBROWSER_ORDER_ADDEDTIME );
m_BigCoverBackBtn->Unbind( wxEVT_BUTTON, &guAlbumBrowser::OnBigCoverBackClicked, this );
m_BigCoverBitmap->Unbind( wxEVT_LEFT_DOWN, &guAlbumBrowser::OnBigCoverBitmapClicked, this );
m_BigCoverBitmap->Unbind( wxEVT_LEFT_DCLICK, &guAlbumBrowser::OnBigCoverBitmapDClicked, this );
m_BigCoverTracksListBox->Unbind( wxEVT_LISTBOX_DCLICK, &guAlbumBrowser::OnBigCoverTracksDClicked, this );
m_BigCoverBitmap->Unbind( wxEVT_CONTEXT_MENU, &guAlbumBrowser::OnBigCoverContextMenu, this );
m_BigCoverTracksListBox->Unbind( wxEVT_CONTEXT_MENU, &guAlbumBrowser::OnBigCoverTracksContextMenu, this );
Unbind( wxEVT_TIMER, &guAlbumBrowser::OnTimerTimeout, this, guALBUMBROWSER_TIMER_ID_BITMAP_CLICKED );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverPlayClicked, this, ID_ALBUMBROWSER_PLAY );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEnqueueClicked, this, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEditLabelsClicked, this, ID_ALBUMBROWSER_EDITLABELS );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEditTracksClicked, this, ID_ALBUMBROWSER_EDITTRACKS );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCopyToClipboard, this, ID_ALBUMBROWSER_COPYTOCLIPBOARD );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverAlbumSelectName, this, ID_ALBUM_SELECTNAME );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverArtistSelectName, this, ID_ARTIST_SELECTNAME );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverDownloadCoverClicked, this, ID_ALBUMBROWSER_SEARCHCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverSelectCoverClicked, this, ID_ALBUMBROWSER_SELECTCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverDeleteCoverClicked, this, ID_ALBUMBROWSER_DELETECOVER );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEmbedCoverClicked, this, ID_ALBUMBROWSER_EMBEDCOVER );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksPlayClicked, this, ID_ALBUMBROWSER_TRACKS_PLAY );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEnqueueClicked, this, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEditLabelsClicked, this, ID_ALBUMBROWSER_TRACKS_EDITLABELS );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEditTracksClicked, this, ID_ALBUMBROWSER_TRACKS_EDITTRACKS );
m_BigCoverTracksListBox->Unbind( wxEVT_LEFT_DOWN, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
m_BigCoverTracksListBox->Unbind( wxEVT_LEFT_UP, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
m_BigCoverTracksListBox->Unbind( wxEVT_MOTION, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksBeginDrag, this, ID_ALBUMBROWSER_TRACKS_BEGINDRAG );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksPlaylistSave, this, ID_ALBUMBROWSER_TRACKS_PLAYLIST_SAVE );
Unbind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksSmartPlaylist, this, ID_ALBUMBROWSER_TRACKS_SMART_PLAYLIST );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::CreateControls( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_SortSelected = Config->ReadNum( wxT( "Sort" ), guALBUMS_ORDER_ARTIST_YEAR_REVERSE, m_ConfigPath );
// GUI
SetMinSize( wxSize( 120, 150 ) );
m_MainSizer = new wxBoxSizer( wxVERTICAL );
// AlbumItems
m_AlbumBrowserSizer = new wxBoxSizer( wxVERTICAL );
m_AlbumsSizer = new wxGridSizer( 1, 1, 0, 0 );
m_ItemPanels.Add( new guAlbumBrowserItemPanel( this, 0 ) );
m_AlbumsSizer->Add( m_ItemPanels[ 0 ], 1, wxEXPAND|wxALL, 5 );
m_AlbumBrowserSizer->Add( m_AlbumsSizer, 1, wxEXPAND, 5 );
// Navigator
wxBoxSizer * NavigatorSizer = new wxBoxSizer( wxVERTICAL );
m_NavLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_NavLabel->Wrap( -1 );
NavigatorSizer->Add( m_NavLabel, 0, wxRIGHT|wxLEFT|wxEXPAND, 5 );
m_NavSlider = new wxSlider( this, wxID_ANY, 0, 0, 1, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL );
m_NavSlider->SetFocus();
NavigatorSizer->Add( m_NavSlider, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
m_AlbumBrowserSizer->Add( NavigatorSizer, 0, wxEXPAND, 5 );
m_MainSizer->Add( m_AlbumBrowserSizer, 1, wxEXPAND, 5 );
// BigCover
// ------------------------------------------------------------------------------------------------------------------
m_BigCoverSizer = new wxBoxSizer( wxVERTICAL );
m_BigCoverSizer->Add( 0, 0, 1, wxEXPAND, 5 );
wxFlexGridSizer * BigCoverCenterSizer = new wxFlexGridSizer( 5, 0, 0 );
BigCoverCenterSizer->AddGrowableCol( 0 );
BigCoverCenterSizer->AddGrowableCol( 2 );
BigCoverCenterSizer->AddGrowableCol( 3 );
BigCoverCenterSizer->AddGrowableCol( 4 );
BigCoverCenterSizer->SetFlexibleDirection( wxBOTH );
BigCoverCenterSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
BigCoverCenterSizer->Add( 0, 0, 2, wxEXPAND, 5 );
wxBoxSizer * BigCoverSizer = new wxBoxSizer( wxVERTICAL );
m_BigCoverBitmap = new wxStaticBitmap( this, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize( 300, 300 ), 0 );
BigCoverSizer->Add( m_BigCoverBitmap, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
m_BigCoverAlbumLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 290, -1 ) );
wxFont CurFont = GetFont();
CurFont.SetWeight( wxFONTWEIGHT_BOLD );
m_BigCoverAlbumLabel->SetFont( CurFont );
BigCoverSizer->Add( m_BigCoverAlbumLabel, 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_BigCoverArtistLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 290, -1 ) );
//m_BigCoverArtistLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );
BigCoverSizer->Add( m_BigCoverArtistLabel, 0, wxALIGN_CENTER_HORIZONTAL|wxRIGHT|wxLEFT, 5 );
m_BigCoverDetailsLabel = new guAutoScrollText( this, wxEmptyString, wxSize( 290, -1 ) );
CurFont = GetFont();
CurFont.SetPointSize( CurFont.GetPointSize() - 2 );
m_BigCoverDetailsLabel->SetFont( CurFont );
BigCoverSizer->Add( m_BigCoverDetailsLabel, 0, wxALIGN_CENTER_HORIZONTAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
BigCoverCenterSizer->Add( BigCoverSizer, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
BigCoverCenterSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_BigCoverTracksListBox = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_MULTIPLE );
//m_BigCoverTracksListBox->SetBackgroundColour( m_BigCoverDetailsLabel->GetBackgroundColour() );
m_BigCoverTracksListBox->SetMaxSize( wxSize( 450, -1 ) );
BigCoverCenterSizer->Add( m_BigCoverTracksListBox, 1, wxEXPAND|wxRIGHT, 5 );
BigCoverCenterSizer->Add( 0, 0, 2, wxEXPAND, 5 );
m_BigCoverSizer->Add( BigCoverCenterSizer, 0, wxEXPAND, 5 );
m_BigCoverSizer->Add( 0, 0, 1, wxEXPAND, 5 );
wxBoxSizer * BigCoverBtnSizer = new wxBoxSizer( wxVERTICAL );
m_BigCoverBackBtn = new wxButton( this, wxID_ANY, _( "Back" ), wxDefaultPosition, wxDefaultSize, 0 );
BigCoverBtnSizer->Add( m_BigCoverBackBtn, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
m_BigCoverSizer->Add( BigCoverBtnSizer, 0, wxEXPAND, 5 );
m_BigCoverSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_MainSizer->Add( m_BigCoverSizer, 1, wxEXPAND, 5 );
// ------------------------------------------------------------------------------------------------------------------
this->SetSizer( m_MainSizer );
BigCoverSizer->Layout();
m_MainSizer->Hide( m_BigCoverSizer, true );
m_MainSizer->FitInside( this );
Bind( wxEVT_SIZE, &guAlbumBrowser::OnChangedSize, this );
Bind( wxEVT_KEY_DOWN, &guAlbumBrowser::OnKeyDown, this );
m_NavSlider->Bind( wxEVT_SCROLL_CHANGED, &guAlbumBrowser::OnChangingPosition, this );
m_NavSlider->Bind( wxEVT_SCROLL_THUMBTRACK, &guAlbumBrowser::OnChangingPosition, this );
Bind( wxEVT_TIMER, &guAlbumBrowser::OnRefreshTimer, this, guALBUMBROWSER_TIMER_ID_REFRESH );
Bind( wxEVT_MENU, &guAlbumBrowser::OnUpdateDetails, this, ID_ALBUMBROWSER_UPDATEDETAILS );
Bind( wxEVT_MOUSEWHEEL, &guAlbumBrowser::OnMouseWheel, this );
Bind( wxEVT_MENU, &guAlbumBrowser::OnGoToSearch, this, ID_ALBUMBROWSER_SEARCH );
Bind( guConfigUpdatedEvent, &guAlbumBrowser::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guAlbumBrowser::OnSortSelected, this, ID_ALBUMBROWSER_ORDER_NAME, ID_ALBUMBROWSER_ORDER_ADDEDTIME );
m_BigCoverBackBtn->Bind( wxEVT_BUTTON, &guAlbumBrowser::OnBigCoverBackClicked, this );
m_BigCoverBitmap->Bind( wxEVT_LEFT_DOWN, &guAlbumBrowser::OnBigCoverBitmapClicked, this );
m_BigCoverBitmap->Bind( wxEVT_LEFT_DCLICK, &guAlbumBrowser::OnBigCoverBitmapDClicked, this );
m_BigCoverTracksListBox->Bind( wxEVT_LISTBOX_DCLICK, &guAlbumBrowser::OnBigCoverTracksDClicked, this );
m_BigCoverBitmap->Bind( wxEVT_CONTEXT_MENU, &guAlbumBrowser::OnBigCoverContextMenu, this );
m_BigCoverTracksListBox->Bind( wxEVT_CONTEXT_MENU, &guAlbumBrowser::OnBigCoverTracksContextMenu, this );
Bind( wxEVT_TIMER, &guAlbumBrowser::OnTimerTimeout, this, guALBUMBROWSER_TIMER_ID_BITMAP_CLICKED );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverPlayClicked, this, ID_ALBUMBROWSER_PLAY );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEnqueueClicked, this, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEditLabelsClicked, this, ID_ALBUMBROWSER_EDITLABELS );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEditTracksClicked, this, ID_ALBUMBROWSER_EDITTRACKS );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCopyToClipboard, this, ID_ALBUMBROWSER_COPYTOCLIPBOARD );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverAlbumSelectName, this, ID_ALBUM_SELECTNAME );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverArtistSelectName, this, ID_ARTIST_SELECTNAME );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverDownloadCoverClicked, this, ID_ALBUMBROWSER_SEARCHCOVER );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverSelectCoverClicked, this, ID_ALBUMBROWSER_SELECTCOVER );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverDeleteCoverClicked, this, ID_ALBUMBROWSER_DELETECOVER );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverEmbedCoverClicked, this, ID_ALBUMBROWSER_EMBEDCOVER );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksPlayClicked, this, ID_ALBUMBROWSER_TRACKS_PLAY );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEnqueueClicked, this, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ALL, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEditLabelsClicked, this, ID_ALBUMBROWSER_TRACKS_EDITLABELS );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksEditTracksClicked, this, ID_ALBUMBROWSER_TRACKS_EDITTRACKS );
m_BigCoverTracksListBox->Bind( wxEVT_LEFT_DOWN, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
m_BigCoverTracksListBox->Bind( wxEVT_LEFT_UP, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
m_BigCoverTracksListBox->Bind( wxEVT_MOTION, &guAlbumBrowser::OnBigCoverTracksMouseMoved, this );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksBeginDrag, this, ID_ALBUMBROWSER_TRACKS_BEGINDRAG );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksPlaylistSave, this, ID_ALBUMBROWSER_TRACKS_PLAYLIST_SAVE );
Bind( wxEVT_MENU, &guAlbumBrowser::OnBigCoverTracksSmartPlaylist, this, ID_ALBUMBROWSER_TRACKS_SMART_PLAYLIST );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
int guAlbumBrowser::GetContextMenuFlags( void )
{
return m_MediaViewer->GetContextMenuFlags();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_ALBUMBROWSER_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnGoToSearch( wxCommandEvent &event )
{
m_MediaViewer->GoToSearch();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::CalculateMaxItemHeight( void )
{
int w;
int h;
int d;
GetTextExtent( wxT("Hg"), &w, &h, &d );
guALBUMBROWSER_GRID_SIZE_HEIGHT = GUCOVER_IMAGE_SIZE + 4 + ( 3 * h ) + 5;
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnChangedSize( wxSizeEvent &event )
{
wxSize Size = event.GetSize();
if( ( Size != m_LastSize ) )
{
size_t ColItems = Size.GetWidth() / guALBUMBROWSER_GRID_SIZE_WIDTH;
size_t RowItems = Size.GetHeight() / guALBUMBROWSER_GRID_SIZE_HEIGHT;
//guLogMessage( wxT( "Row: %i Col:%i" ), RowItems, ColItems );
if( ColItems * RowItems != m_ItemPanels.Count() )
{
size_t OldCount = m_ItemPanels.Count();
m_ItemCount = ColItems * RowItems;
//guLogMessage( wxT( "We need to reassign the panels from %li to %i" ), OldCount, m_ItemCount );
if( OldCount != m_ItemCount )
{
m_AlbumItemsMutex.Lock();
m_AlbumsSizer->SetCols( ColItems );
m_AlbumsSizer->SetRows( RowItems );
if( OldCount < m_ItemCount )
{
while( m_ItemPanels.Count() < m_ItemCount )
{
int Index = m_ItemPanels.Count();
m_ItemPanels.Add( new guAlbumBrowserItemPanel( this, Index ) );
if( m_BigCoverShowed )
m_ItemPanels[ Index ]->Hide();
m_AlbumsSizer->Add( m_ItemPanels[ Index ], 1, wxEXPAND|wxALL, 2 );
}
}
else //if( m_ItemCount < OldCount )
{
//size_t Count;
for( size_t Index = OldCount; Index > m_ItemCount; Index-- )
{
guAlbumBrowserItemPanel * ItemPanel = m_ItemPanels[ Index - 1 ];
m_AlbumsSizer->Detach( ItemPanel );
m_ItemPanels.RemoveAt( Index - 1 );
delete ItemPanel;
}
}
m_AlbumItemsMutex.Unlock();
RefreshPageCount();
ReloadItems();
RefreshAll();
}
}
m_LastSize = Size;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::RefreshCount( void )
{
m_AlbumsCount = m_Db->GetAlbumsCount( m_DynFilter.IsEmpty() ? NULL : &m_DynFilter, m_TextSearchFilter );
//m_ItemStart = 0;
RefreshPageCount();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::ClearUpdateDetailsThread( void )
{
m_UpdateDetailsMutex.Lock();
m_UpdateDetails = NULL;
m_UpdateDetailsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::RefreshPageCount( void )
{
if( m_ItemCount && m_AlbumsCount )
{
m_PagesCount = m_AlbumsCount / m_ItemCount;
if( ( m_PagesCount * m_ItemCount ) < m_AlbumsCount )
m_PagesCount++;
}
else
{
m_PagesCount = 0;
}
//guLogMessage( wxT( "RefreshPageCount: Albums: %i Items: %i Pages: %i" ), m_AlbumsCount, m_ItemCount, m_PagesCount );
UpdateNavLabel( 0 );
m_NavSlider->Enable( m_PagesCount > 1 );
if( m_PagesCount > 1 )
m_NavSlider->SetRange( 0, m_PagesCount - 1 );
//else
// m_NavSlider->SetRange( 0, 0 );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::SetCurrentPage( int page )
{
m_NavSlider->SetValue( page );
wxScrollEvent ScrollEvent( wxEVT_SCROLL_CHANGED );
ScrollEvent.SetPosition( page );
wxPostEvent( m_NavSlider, ScrollEvent );
}
// -------------------------------------------------------------------------------- //
bool guAlbumBrowser::DoTextSearch( const wxString &searchtext )
{
if( m_LastSearchString != searchtext )
{
m_LastSearchString = searchtext; //m_SearchTextCtrl->GetValue();
if( !m_LastSearchString.IsEmpty() )
{
if( m_LastSearchString.Length() > 0 )
{
m_TextSearchFilter = guSplitWords( m_LastSearchString );
RefreshCount();
m_LastItemStart = wxNOT_FOUND;
SetCurrentPage( 0 );
// m_SearchTextCtrl->ShowCancelButton( true );
}
return true;
}
else
{
m_TextSearchFilter.Clear();
RefreshCount();
m_LastItemStart = wxNOT_FOUND;
SetCurrentPage( 0 );
// m_SearchTextCtrl->ShowCancelButton( false );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::ReloadItems( void )
{
m_AlbumItemsMutex.Lock();
m_AlbumItems.Empty();
m_Db->GetAlbums( &m_AlbumItems, m_DynFilter.IsEmpty() ? NULL : &m_DynFilter,
m_TextSearchFilter, m_ItemStart, m_ItemCount, m_SortSelected );
m_AlbumItemsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::RefreshAll( void )
{
m_UpdateDetailsMutex.Lock();
if( m_UpdateDetails )
{
m_UpdateDetails->Pause();
m_UpdateDetails->Delete();
}
m_UpdateDetails = new guUpdateAlbumDetails( this );
m_UpdateDetailsMutex.Unlock();
m_AlbumItemsMutex.Lock();
unsigned int Count = m_ItemCount;
for( unsigned int Index = 0; Index < Count; Index++ )
{
//guLogMessage( wxT( "%li %s " ), Index, m_AlbumItems[ Index ].m_AlbumName.c_str() );
if( Index < m_AlbumItems.Count() )
m_ItemPanels[ Index ]->SetAlbumItem( Index, &m_AlbumItems[ Index ], m_BlankCD );
else
m_ItemPanels[ Index ]->SetAlbumItem( Index, NULL, m_BlankCD );
}
m_AlbumItemsMutex.Unlock();
Layout();
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnChangingPosition( wxScrollEvent& event )
{
int CurPage = event.GetPosition(); //( ( event.GetPosition() * m_PagesCount ) / 100 );
m_ItemStart = CurPage * m_ItemCount;
//guLogMessage( wxT( "ChangePosition: %i -> %i Albums(%i / %i)" ), m_ItemStart, m_LastItemStart, CurPage, m_AlbumsCount );
if( m_LastItemStart != m_ItemStart )
{
m_RefreshTimer.Start( guALBUMBROWSER_REFRESH_DELAY, wxTIMER_ONE_SHOT );
UpdateNavLabel( CurPage );
// ReloadItems();
// RefreshAll();
m_LastItemStart = m_ItemStart;
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnRefreshTimer( wxTimerEvent &event )
{
ReloadItems();
RefreshAll();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::SelectAlbum( const int albumid, const bool append, const int aftercurrent )
{
guTrackArray Tracks;
wxArrayInt Selections;
Selections.Add( albumid );
if( m_Db->GetAlbumsSongs( Selections, &Tracks, true ) )
{
NormalizeTracks( &Tracks );
if( append )
m_PlayerPanel->AddToPlayList( Tracks, true, aftercurrent );
else
m_PlayerPanel->SetPlayList( Tracks );
}
}
// -------------------------------------------------------------------------------- //
int guAlbumBrowser::GetAlbumTracks( const int albumid, guTrackArray * tracks )
{
wxArrayInt Albums;
Albums.Add( albumid );
return m_Db->GetAlbumsSongs( Albums, tracks, true );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::SetFilter( const wxString &filterstr )
{
m_DynFilter.FromString( filterstr.AfterFirst( wxT( ':' ) ) );
RefreshCount();
m_LastItemStart = wxNOT_FOUND;
SetCurrentPage( 0 );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnSortSelected( wxCommandEvent &event )
{
m_SortSelected = event.GetId() - ID_ALBUMBROWSER_ORDER_NAME;
m_LastItemStart = wxNOT_FOUND;
SetCurrentPage( 0 );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnCommandClicked( const int cmdid, const int albumid )
{
wxArrayInt Selection;
Selection.Add( albumid );
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
int CommandIndex = cmdid - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayString AlbumPaths = m_Db->GetAlbumsPaths( Selection );
wxString Paths = wxEmptyString;
int count = AlbumPaths.Count();
for( int index = 0; index < count; index++ )
{
AlbumPaths[ index ].Replace( wxT( " " ), wxT( "\\ " ) );
//Paths += wxT( " \"" ) + AlbumPaths[ index ] + wxT( "\"" );
Paths += wxT( " " ) + AlbumPaths[ index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
int CoverId = m_Db->GetAlbumCoverId( Selection[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
wxString SongList = wxEmptyString;
if( m_Db->GetAlbumsSongs( Selection, &Songs, true ) )
{
NormalizeTracks( &Songs );
int count = Songs.Count();
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + Songs[ index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnCommandClicked( const int cmdid, const guTrackArray &tracks )
{
if( tracks.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
int CommandIndex = cmdid - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayString AlbumPaths;
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxString Path = wxPathOnly( tracks[ Index ].m_FileName ) + wxT( "/" );
if( AlbumPaths.Index( Path ) == wxNOT_FOUND )
AlbumPaths.Add( Path );
}
wxString Paths = wxEmptyString;
Count = AlbumPaths.Count();
for( int Index = 0; Index < Count; Index++ )
{
AlbumPaths[ Index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ Index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
wxArrayInt AlbumList;
AlbumList.Add( tracks[ 0 ].m_AlbumId );
int CoverId = m_Db->GetAlbumCoverId( AlbumList[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
wxString SongList = wxEmptyString;
int Count = tracks.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
SongList += wxT( " \"" ) + tracks[ Index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumDownloadCoverClicked( const int albumid )
{
m_MediaViewer->DownloadAlbumCover( albumid );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumSelectCoverClicked( const int albumid )
{
m_MediaViewer->SelectAlbumCover( albumid );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumDeleteCoverClicked( const int albumid )
{
m_MediaViewer->DeleteAlbumCover( albumid );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumEmbedCoverClicked( const int albumid )
{
m_MediaViewer->EmbedAlbumCover( albumid );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumCopyToClicked( const int albumid, const int commandid )
{
guTrackArray * Tracks = new guTrackArray();
wxArrayInt Albums;
Albums.Add( albumid );
m_Db->GetAlbumsSongs( Albums, Tracks, true );
NormalizeTracks( Tracks );
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_COPYTO );
int Index = commandid - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumEditLabelsClicked( const guAlbumBrowserItem * albumitem )
{
guListItems Albums;
Albums.Add( new guListItem( albumitem->m_AlbumId, albumitem->m_AlbumName ) );
// if( Albums.Count() )
// {
wxArrayInt AlbumIds;
AlbumIds.Add( albumitem->m_AlbumId );
guArrayListItems LabelSets = m_Db->GetAlbumsLabels( AlbumIds );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Albums Labels Editor" ),
false, &Albums, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
m_Db->UpdateAlbumsLabels( LabelSets );
}
LabelEditor->Destroy();
// if( m_FilterBtn->GetValue() ) // If its filtered we may need to refresh as the filter can contains the label condition
{
ReloadItems();
RefreshAll();
}
}
// }
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumEditTracksClicked( const int albumid )
{
guTrackArray Songs;
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
//m_AlbumListCtrl->GetSelectedSongs( &Songs );
wxArrayInt Albums;
Albums.Add( albumid );
m_Db->GetAlbumsSongs( Albums, &Songs, true );
if( !Songs.Count() )
return;
NormalizeTracks( &Songs );
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Songs, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
guUpdateTracks( Songs, Images, Lyrics, ChangedFlags );
m_Db->UpdateSongs( &Songs, ChangedFlags );
//guUpdateLyrics( Songs, Lyrics, ChangedFlags );
//guUpdateImages( Songs, Images, ChangedFlags );
m_PlayerPanel->UpdatedTracks( &Songs );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnUpdateDetails( wxCommandEvent &event )
{
m_AlbumItemsMutex.Lock();
//guLogMessage( wxT( "OnUpdateDetails %i - %li" ), event.GetInt(), m_ItemPanels.GetCount() );
int Count = m_ItemPanels.GetCount();
for( int Index = 0; Index < Count; Index++ )
{
m_ItemPanels[ Index ]->UpdateDetails();
}
Layout();
m_AlbumItemsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnKeyDown( wxKeyEvent &event )
{
//guLogMessage( wxT( "OnKeyDown %i" ), event.GetKeyCode() );
int CurPos = m_NavSlider->GetValue();
int KeyCode = event.GetKeyCode();
switch( KeyCode )
{
case WXK_HOME :
CurPos = m_NavSlider->GetMin();
break;
case WXK_END :
CurPos = m_NavSlider->GetMax();
break;
case WXK_DOWN :
case WXK_RIGHT :
case WXK_NUMPAD_DOWN :
CurPos++;
break;
case WXK_UP :
case WXK_LEFT :
case WXK_NUMPAD_UP :
CurPos--;
break;
case WXK_PAGEDOWN :
case WXK_NUMPAD_PAGEDOWN :
CurPos += m_NavSlider->GetPageSize();
break;
case WXK_PAGEUP :
case WXK_NUMPAD_PAGEUP :
CurPos -= m_NavSlider->GetPageSize();
break;
}
if( CurPos > m_NavSlider->GetMax() )
CurPos = m_NavSlider->GetMax();
if( CurPos < m_NavSlider->GetMin() )
CurPos = m_NavSlider->GetMin();
SetCurrentPage( CurPos );
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnMouseWheel( wxMouseEvent& event )
{
if( m_BigCoverShowed || !m_NavSlider->IsEnabled() )
{
event.Skip();
return;
}
int Rotation = event.GetWheelRotation() / event.GetWheelDelta() * -1;
//guLogMessage( wxT( "Got MouseWheel %i " ), Rotation );
int CurPos = m_NavSlider->GetValue() + Rotation;
if( CurPos > m_NavSlider->GetMax() )
CurPos = m_NavSlider->GetMax();
if( CurPos < m_NavSlider->GetMin() )
CurPos = m_NavSlider->GetMin();
SetCurrentPage( CurPos );
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::LibraryUpdated( void )
{
int CurPage = m_NavSlider->GetValue();
RefreshCount();
if( CurPage > m_NavSlider->GetMax() )
CurPage = m_NavSlider->GetMax();
m_ItemStart = CurPage * m_ItemCount;
UpdateNavLabel( CurPage );
ReloadItems();
RefreshAll();
}
// -------------------------------------------------------------------------------- //
wxString guAlbumBrowser::GetAlbumCoverFile( const int coverid )
{
return m_Db->GetCoverPath( coverid );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::SetAlbumCover( const int albumid, const wxString &cover )
{
wxString AlbumPath;
if( m_Db->GetAlbumInfo( albumid, NULL, NULL, &AlbumPath ) )
{
wxImage CoverImage( cover );
if( CoverImage.IsOk() )
{
wxString CoverName = AlbumPath + m_MediaViewer->CoverName() + wxT( ".jpg" );
if( CoverImage.SaveFile( CoverName, wxBITMAP_TYPE_JPEG ) )
{
m_Db->SetAlbumCover( albumid, CoverName );
}
}
else
{
guLogError( wxT( "Could not load the imate '%s'" ), cover.c_str() );
}
ReloadItems();
RefreshAll();
//
wxCommandEvent evt( wxEVT_MENU, ID_ALBUM_COVER_CHANGED );
evt.SetInt( albumid );
evt.SetClientData( NULL );
wxPostEvent( guMainFrame::GetMainFrame(), evt );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBitmapClicked( guAlbumBrowserItem * albumitem, const wxPoint &position )
{
if( albumitem && albumitem->m_AlbumId )
{
wxImage * Image = NULL;
wxString CoverFile = GetAlbumCoverFile( albumitem->m_CoverId );
if( !CoverFile.IsEmpty() )
{
Image = new wxImage( CoverFile, wxBITMAP_TYPE_ANY );
if( Image && !Image->IsOk() )
{
delete Image;
Image = NULL;
}
}
if( !Image )
{
Image = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
}
guImageResize( Image, 300, true );
m_BigCoverBitmap->SetBitmap( wxBitmap( * Image ) );
if( Image )
{
delete Image;
}
m_BigCoverTracks.Empty();
wxArrayInt Albums;
Albums.Add( albumitem->m_AlbumId );
m_Db->GetAlbumsSongs( Albums, &m_BigCoverTracks, true );
m_MediaViewer->NormalizeTracks( &m_BigCoverTracks );
m_BigCoverTracksListBox->Clear();
m_BigCoverTracksListBox->Append( _( "All" ) );
wxUint64 AlbumLength = 0;
int Count = m_BigCoverTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = m_BigCoverTracks[ Index ];
AlbumLength += Track.m_Length;
wxString TrackName = wxString::Format( wxT( "%02u - " ), Track.m_Number );
if( !Track.m_AlbumArtist.IsEmpty() )
{
TrackName += Track.m_ArtistName + wxT( " - " );
}
TrackName += Track.m_SongName;
m_BigCoverTracksListBox->Append( TrackName );
}
m_BigCoverAlbumLabel->SetLabel( albumitem->m_AlbumName );
m_BigCoverArtistLabel->SetLabel( albumitem->m_ArtistName );
wxString Details;
if( albumitem->m_Year )
{
Details += wxString::Format( wxT( "%04u" ), albumitem->m_Year );
}
Details += wxString::Format( wxT( " %02lu " ), m_BigCoverTracks.Count() );
Details += _( "Tracks" );
if( AlbumLength )
{
Details += wxT( " " ) + LenToString( AlbumLength );
}
m_BigCoverDetailsLabel->SetLabel( Details );
m_LastAlbumBrowserItem = albumitem;
m_BigCoverShowed = true;
m_MainSizer->Hide( m_AlbumBrowserSizer, true );
m_MainSizer->Show( m_BigCoverSizer, true );
Layout();
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnAlbumSelectName( const int albumid )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ALBUM );
evt.SetInt( albumid );
evt.SetClientData( m_MediaViewer );
//evt.SetExtraLong( guTRACK_TYPE_DB );
wxPostEvent( guMainFrame::GetMainFrame(), evt );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnArtistSelectName( const int artistid )
{
wxCommandEvent evt( wxEVT_MENU, ID_MAINFRAME_SELECT_ARTIST );
evt.SetInt( artistid );
evt.SetClientData( m_MediaViewer );
//evt.SetExtraLong( guTRACK_TYPE_DB );
wxPostEvent( guMainFrame::GetMainFrame(), evt );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::UpdateNavLabel( const int page )
{
m_NavLabel->SetLabel( _( "Page" ) + wxString::Format( wxT( " %i / %i" ), page + 1, m_PagesCount ) );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
m_MediaViewer->NormalizeTracks( tracks, isdrag );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::AlbumCoverChanged( const int albumid )
{
if( m_BigCoverShowed && ( m_LastAlbumBrowserItem->m_AlbumId == ( unsigned int ) albumid ) )
{
wxImage * Image = NULL;
wxString CoverFile = GetAlbumCoverFile( m_LastAlbumBrowserItem->m_CoverId );
if( !CoverFile.IsEmpty() )
{
Image = new wxImage( CoverFile, wxBITMAP_TYPE_ANY );
if( Image && !Image->IsOk() )
{
delete Image;
Image = NULL;
}
}
if( !Image )
{
Image = new wxImage( guImage( guIMAGE_INDEX_no_cover ) );
}
guImageResize( Image, 300, true );
m_BigCoverBitmap->SetBitmap( wxBitmap( * Image ) );
if( Image )
{
delete Image;
}
}
ReloadItems();
// When we do the ReloadItems the m_LastAlbumBrowser pointer is invalid so find it again
int Count = m_AlbumItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_AlbumItems[ Index ].m_AlbumId == ( unsigned int ) albumid )
{
m_LastAlbumBrowserItem = &m_AlbumItems[ Index ];
}
}
RefreshAll();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::CreateContextMenu( wxMenu * menu )
{
m_MediaViewer->CreateContextMenu( menu, guLIBRARY_ELEMENT_ALBUMS );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverBackClicked( wxCommandEvent &event )
{
DoBackToAlbums();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverBitmapClicked( wxMouseEvent &event )
{
guLogMessage( wxT( "OnBigCoverBitmapClicked..." ) );
if( m_BitmapClickTimer.IsRunning() )
m_BitmapClickTimer.Stop();
m_BitmapClickTimer.Start( 300, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverBitmapDClicked( wxMouseEvent &event )
{
if( m_BitmapClickTimer.IsRunning() )
m_BitmapClickTimer.Stop();
DoSelectTracks( m_BigCoverTracks, false );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnTimerTimeout( wxTimerEvent &event )
{
guLogMessage( wxT( "OnBigCoverBitmapClicked...Timeout..." ) );
DoBackToAlbums();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::DoBackToAlbums( void )
{
m_BigCoverShowed = false;
m_MainSizer->Hide( m_BigCoverSizer, true );
m_MainSizer->Show( m_AlbumBrowserSizer, true );
Layout();
m_NavSlider->SetFocus();
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksDClicked( wxCommandEvent &event )
{
guLogMessage( wxT( "TracksDClicked..." ) );
guTrackArray Tracks;
if( GetSelectedTracks( &Tracks ) )
{
DoSelectTracks( Tracks, false );
}
}
// -------------------------------------------------------------------------------- //
int guAlbumBrowser::GetSelectedTracks( guTrackArray * tracks )
{
wxArrayInt Selections;
int Count = m_BigCoverTracksListBox->GetSelections( Selections );
if( Selections.Index( 0 ) != wxNOT_FOUND )
{
* tracks = m_BigCoverTracks;
}
else
{
for( int Index = 0; Index < Count; Index++ )
{
tracks->Add( new guTrack( m_BigCoverTracks[ Selections[ Index ] - 1 ] ) );
}
}
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::DoSelectTracks( const guTrackArray &tracks, const bool append, const int aftercurrent )
{
if( append )
m_PlayerPanel->AddToPlayList( tracks, true, aftercurrent );
else
m_PlayerPanel->SetPlayList( tracks );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverContextMenu( wxContextMenuEvent &event )
{
m_BigCoverTracksContextMenu = false;
wxMenu Menu;
wxMenuItem * MenuItem;
wxPoint Point = event.GetPosition();
// If from keyboard
if( Point.x == -1 && Point.y == -1 )
{
wxSize Size = GetSize();
Point.x = Size.x / 2;
Point.y = Size.y / 2;
}
else
{
Point = ScreenToClient( Point );
}
int ContextMenuFlags = m_MediaViewer->GetContextMenuFlags();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_PLAY, _( "Play" ), _( "Play the album tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL, _( "Enqueue" ), _( "Enqueue the album tracks to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu.Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu.Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EDITLABELS, _( "Edit Labels" ), _( "Edit the labels assigned to the selected albums" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu.Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EDITTRACKS, _( "Edit Songs" ), _( "Edit the selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUM_SELECTNAME, _( "Search Album" ), _( "Search the album in the library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_search ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ARTIST_SELECTNAME, _( "Search Artist" ), _( "Search the artist in the library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_search ) );
Menu.Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_DOWNLOAD_COVERS )
{
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_SEARCHCOVER, _( "Download Cover" ), _( "Download cover for the current selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_SELECTCOVER, _( "Select Cover" ), _( "Select the cover image file from disk" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_DELETECOVER, _( "Delete Cover" ), _( "Delete the cover for the selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_delete ) );
Menu.Append( MenuItem );
}
if( ContextMenuFlags & guCONTEXTMENU_EMBED_COVERS )
{
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_EMBEDCOVER, _( "Embed Cover" ), _( "Embed the cover to the selected album tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_COPYTOCLIPBOARD, _( "Copy to Clipboard" ), _( "Copy the album info to clipboard" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_copy ) );
Menu.Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu.AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
MainFrame->CreateCopyToMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_LINKS )
{
AddOnlineLinksMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
{
AddAlbumCommands( &Menu, 1 );
}
}
CreateContextMenu( &Menu );
// Add Links and Commands
PopupMenu( &Menu, Point.x, Point.y );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksContextMenu( wxContextMenuEvent &event )
{
m_BigCoverTracksContextMenu = true;
wxMenu Menu;
wxMenuItem * MenuItem;
wxPoint Point = event.GetPosition();
// If from keyboard
if( Point.x == -1 && Point.y == -1 )
{
wxSize Size = GetSize();
Point.x = Size.x / 2;
Point.y = Size.y / 2;
}
else
{
Point = ScreenToClient( Point );
}
int ContextMenuFlags = m_MediaViewer->GetContextMenuFlags();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_PLAY, _( "Play" ), _( "Play the album tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ALL, _( "Enqueue" ), _( "Enqueue the album tracks to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu.Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu.Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_EDITLABELS, _( "Edit Labels" ), _( "Edit the labels assigned to the selected albums" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu.Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_EDITTRACKS, _( "Edit Songs" ), _( "Edit the selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_PLAYLIST_SAVE,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_ALBUMBROWSER_TRACKS_SMART_PLAYLIST, _( "Create Smart Playlist" ), _( "Create a smart playlist from this track" ) );
Menu.Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu.AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
MainFrame->CreateCopyToMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_LINKS )
{
AddOnlineLinksMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
{
AddAlbumCommands( &Menu, 1 );
}
}
CreateContextMenu( &Menu );
// Add Links and Commands
PopupMenu( &Menu, Point.x, Point.y );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksPlayClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
DoSelectTracks( Tracks, false );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksEnqueueClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
DoSelectTracks( Tracks, true, event.GetId() - ID_ALBUMBROWSER_TRACKS_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksEditLabelsClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
if( Tracks.Count() )
{
guListItems TrackItems;
wxArrayInt TrackIds;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
TrackItems.Add( new guListItem( Tracks[ Index ].m_SongId, Tracks[ Index ].m_SongName ) );
TrackIds.Add( Tracks[ Index ].m_SongId );
}
guArrayListItems LabelSets = m_Db->GetSongsLabels( TrackIds );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Tracks Labels Editor" ), false, &TrackItems, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the files
m_Db->UpdateSongsLabels( LabelSets );
}
LabelEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
for( int Index = Tracks.Count() - 1; Index >= 0; Index-- )
{
if( Tracks[ Index ].m_Offset )
Tracks.RemoveAt( Index );
}
if( Tracks.Count() )
{
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Tracks, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
m_MediaViewer->UpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
// Update the track in database, playlist, etc
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverPlayClicked( wxCommandEvent &event )
{
SelectAlbum( m_LastAlbumBrowserItem->m_AlbumId, false );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverEnqueueClicked( wxCommandEvent &event )
{
SelectAlbum( m_LastAlbumBrowserItem->m_AlbumId, true, event.GetId() - ID_ALBUMBROWSER_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverCopyToClipboard( wxCommandEvent &event )
{
wxTheClipboard->UsePrimarySelection( false );
if( wxTheClipboard->Open() )
{
wxTheClipboard->Clear();
if( !wxTheClipboard->AddData( new wxTextDataObject(
m_LastAlbumBrowserItem->m_ArtistName + wxT( " " ) + m_LastAlbumBrowserItem->m_AlbumName ) ) )
{
guLogError( wxT( "Can't copy data to the clipboard" ) );
}
wxTheClipboard->Close();
}
else
{
guLogError( wxT( "Could not open the clipboard object" ) );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverAlbumSelectName( wxCommandEvent &event )
{
OnAlbumSelectName( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverArtistSelectName( wxCommandEvent &event )
{
OnArtistSelectName( m_LastAlbumBrowserItem->m_ArtistId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverCommandClicked( wxCommandEvent &event )
{
if( !m_BigCoverTracksContextMenu )
{
OnCommandClicked( event.GetId(), m_LastAlbumBrowserItem->m_AlbumId );
}
else
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
OnCommandClicked( event.GetId(), Tracks );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverDownloadCoverClicked( wxCommandEvent &event )
{
OnAlbumDownloadCoverClicked( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverSelectCoverClicked( wxCommandEvent &event )
{
OnAlbumSelectCoverClicked( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverDeleteCoverClicked( wxCommandEvent &event )
{
OnAlbumDeleteCoverClicked( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverEmbedCoverClicked( wxCommandEvent &event )
{
OnAlbumEmbedCoverClicked( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverCopyToClicked( wxCommandEvent &event )
{
if( !m_BigCoverTracksContextMenu )
{
OnAlbumCopyToClicked( m_LastAlbumBrowserItem->m_AlbumId, event.GetId() );
}
else
{
guTrackArray * Tracks = new guTrackArray();
GetSelectedTracks( Tracks );
wxCommandEvent CopyEvent( wxEVT_MENU, ID_MAINFRAME_COPYTO );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
CopyEvent.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
CopyEvent.SetInt( Index );
CopyEvent.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), CopyEvent );
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverEditLabelsClicked( wxCommandEvent &event )
{
OnAlbumEditLabelsClicked( m_LastAlbumBrowserItem );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverEditTracksClicked( wxCommandEvent &event )
{
OnAlbumEditTracksClicked( m_LastAlbumBrowserItem->m_AlbumId );
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverSearchLinkClicked( wxCommandEvent &event )
{
if( !m_BigCoverTracksContextMenu )
{
ExecuteOnlineLink( event.GetId(), m_LastAlbumBrowserItem->m_ArtistName + wxT( " " ) +
m_LastAlbumBrowserItem->m_AlbumName );
}
else
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ExecuteOnlineLink( event.GetId(), Tracks[ Index ].m_ArtistName + wxT( " \"" ) +
Tracks[ Index ].m_SongName + wxT( "\"" ) );
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksMouseMoved( wxMouseEvent &event )
{
int Item = m_BigCoverTracksListBox->HitTest( event.GetPosition() );
bool ResetVals = false;
// We want to get a better experience for dragging as before
// when you click over selected items the items was unselected
// even when you tried to drag then.
// Here we check if the item was selected and if so wait for the button up
// to unselect the item
//guLogMessage( wxT( "Item: %u LD: %i LU: %i SD: %i CD: %i WasLeftUp: %i Selecting: %i Dragging: %i" ),
// Item,
// event.LeftDown(),
// event.LeftUp(),
// event.ShiftDown(),
// event.ControlDown(),
// m_MouseWasLeftUp,
// m_MouseSelecting,
// event.Dragging() );
if( !m_MouseWasLeftUp && !event.ShiftDown() && !event.ControlDown() )
{
m_MouseWasLeftUp = event.LeftUp();
if( ( event.LeftDown() || m_MouseWasLeftUp ) )
{
if( Item != wxNOT_FOUND )
{
bool Selected = m_BigCoverTracksListBox->IsSelected( Item );
if( Selected )
{
if( !m_MouseSelecting && event.LeftUp() )
{
// Its a LeftUp event
event.SetEventType( wxEVT_LEFT_DOWN );
event.m_leftDown = true;
//m_BigCoverTracksListBox->GetEventHandler()->AddPendingEvent( NewEvent );
AddPendingEvent( event );
}
return;
}
m_MouseSelecting = event.LeftDown();
}
}
else
{
ResetVals = true;
}
}
else
{
ResetVals = true;
}
if( event.Dragging() )
{
if( !m_DragCount )
{
m_DragStart = event.GetPosition();
}
if( ++m_DragCount == 3 )
{
wxCommandEvent DragEvent( wxEVT_MENU, ID_ALBUMBROWSER_TRACKS_BEGINDRAG );
DragEvent.SetEventObject( this );
GetEventHandler()->ProcessEvent( DragEvent );
}
return;
}
else
{
m_DragCount = 0;
}
if( ResetVals )
{
m_MouseWasLeftUp = false;
m_MouseSelecting = false;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksBeginDrag( wxCommandEvent &event )
{
//guLogMessage( wxT( "On BeginDrag event..." ) );
guTrackArray Tracks;
int Count = GetSelectedTracks( &Tracks );
if( Count )
{
guDataObjectComposite Files;
wxArrayString Filenames;
for( int Index = 0; Index < Count; Index++ )
{
if( Tracks[ Index ].m_Offset )
continue;
Filenames.Add( guFileDnDEncode( Tracks[ Index ].m_FileName ) );
}
Files.SetTracks( Tracks );
Files.SetFiles( Filenames );
wxDropSource source( Files, this );
wxDragResult Result = source.DoDragDrop( wxDrag_CopyOnly );
if( Result )
{
}
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksPlaylistSave( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
if( Tracks.Count() )
{
wxArrayInt TrackIds;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
TrackIds.Add( Tracks[ Index ].m_SongId );
}
guListItems PlayLists;
m_Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( guMainFrame::GetMainFrame(), m_Db, &TrackIds, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int PLId;
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == -1 )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
PLId = m_Db->CreateStaticPlayList( PLName, TrackIds );
}
else
{
PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
m_Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
m_Db->UpdateStaticPlayList( PLId, TrackIds );
m_Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
m_Db->AppendStaticPlayList( PLId, TrackIds );
}
}
m_Db->UpdateStaticPlayListFile( PLId );
m_MediaViewer->UpdatePlaylists();
}
PlayListAppendDlg->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guAlbumBrowser::OnBigCoverTracksSmartPlaylist( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedTracks( &Tracks );
if( Tracks.Count() )
{
m_MediaViewer->CreateSmartPlaylist( Tracks[ 0 ].m_ArtistName, Tracks[ 0 ].m_SongName );
}
}
// -------------------------------------------------------------------------------- //
wxString guAlbumBrowser::GetSelInfo( void )
{
if( m_BigCoverShowed )
{
return wxString::Format( wxT( "%lu " ), m_BigCoverTracks.Count() ) + _( "Tracks" );
}
else
{
if( m_AlbumsCount > 0 )
{
wxString SelInfo = _( "Albums" ) + wxString::Format( wxT( " %u " ), m_ItemStart + 1 );
SelInfo += _( "to" ) + wxString::Format( wxT( " %u " ), wxMin( m_ItemStart + m_ItemCount, m_AlbumsCount ) );
SelInfo += _( "of" ) + wxString::Format( wxT( " %u " ), m_AlbumsCount );
return SelInfo;
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
// guAlbumBrowserDropTarget
// -------------------------------------------------------------------------------- //
guAlbumBrowserDropTarget::guAlbumBrowserDropTarget( guMediaViewer * mediaviewer, guAlbumBrowserItemPanel * itempanel ) :
wxDropTarget()
{
m_MediaViewer = mediaviewer;
m_AlbumBrowserItemPanel = itempanel;
wxDataObjectComposite * DataObject = new wxDataObjectComposite();
wxCustomDataObject * TracksDataObject = new wxCustomDataObject( wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) );
DataObject->Add( TracksDataObject, true );
wxFileDataObject * FileDataObject = new wxFileDataObject();
DataObject->Add( FileDataObject, false );
SetDataObject( DataObject );
}
// -------------------------------------------------------------------------------- //
wxDragResult guAlbumBrowserDropTarget::OnData( wxCoord x, wxCoord y, wxDragResult def )
{
//guLogMessage( wxT( "guAlbumBrowserDropTarget::OnData" ) );
if( def == wxDragError || def == wxDragNone || def == wxDragCancel )
return def;
if( !GetData() )
{
guLogMessage( wxT( "Error getting drop data" ) );
return wxDragError;
}
guDataObjectComposite * DataObject = ( guDataObjectComposite * ) m_dataObject;
wxDataFormat ReceivedFormat = DataObject->GetReceivedFormat();
//guLogMessage( wxT( "ReceivedFormat: '%s'" ), ReceivedFormat.GetId().c_str() );
if( ReceivedFormat == wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) )
{
guTrackArray * Tracks;
if( !DataObject->GetDataHere( ReceivedFormat, &Tracks ) )
{
guLogMessage( wxT( "Error getting tracks data..." ) );
}
else
{
m_MediaViewer->ImportFiles( new guTrackArray( * Tracks ) );
}
}
else if( ReceivedFormat == wxDataFormat( wxDF_FILENAME ) )
{
wxFileDataObject * FileDataObject = ( wxFileDataObject * ) DataObject->GetDataObject( wxDataFormat( wxDF_FILENAME ) );
if( FileDataObject )
{
wxArrayString Files = FileDataObject->GetFilenames();
if( Files.Count() )
{
wxString CoverFile = Files[ 0 ];
if( !CoverFile.IsEmpty() && wxFileExists( CoverFile ) &&
guIsValidImageFile( CoverFile.Lower() ) )
{
m_AlbumBrowserItemPanel->SetAlbumCover( CoverFile );
}
else
{
m_MediaViewer->ImportFiles( Files );
}
}
}
}
return def;
}
}
// -------------------------------------------------------------------------------- //
| 102,033
|
C++
|
.cpp
| 2,214
| 38.930894
| 182
| 0.583851
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,602
|
TVSoListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/treeview/TVSoListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TVSoListBox.h"
#include "Accelerators.h"
#include "Config.h" // Configuration
#include "EventCommandIds.h"
#include "Images.h"
#include "MainApp.h"
#include "MediaViewer.h"
#include "OnlineLinks.h"
#include "RatingCtrl.h"
#include "TagInfo.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guTVSoListBox::guTVSoListBox( wxWindow * parent, guMediaViewer * mediaviewer, wxString confname, int style ) :
guSoListBox( parent, mediaviewer, confname, style | guLISTVIEW_ALLOWDRAG )
{
// guConfig * Config = ( guConfig * ) guConfig::Get();
// m_TracksOrder = Config->ReadNum( wxT( "TracksOrder" ), 0, confname );
// m_TracksOrderDesc = Config->ReadBool( wxT( "TracksOrderDesc" ), 0, confname );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guTVSoListBox::~guTVSoListBox()
{
// guConfig * Config = ( guConfig * ) guConfig::Get();
// Config->WriteNum( wxT( "TracksOrder" ), m_TracksOrder, m_ConfName );
// Config->WriteBool( wxT( "TracksOrderDesc" ), m_TracksOrderDesc, m_ConfName );
}
// -------------------------------------------------------------------------------- //
void guTVSoListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_TRACKS_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_TRACKS_EDITLABELS );
RealAccelCmds.Add( ID_TRACKS_EDITTRACKS );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_PLAYLIST_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guTVSoListBox::GetItemsList( void )
{
m_Items.Empty();
if( m_Filters.Count() )
{
m_Db->GetSongs( m_Filters, &m_Items, m_TextFilters, m_TracksOrder, m_TracksOrderDesc );
}
SetItemCount( m_Items.Count() );
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guTVSoListBox::SetFilters( guTreeViewFilterArray &filters )
{
m_Filters = filters;
ReloadItems();
}
// -------------------------------------------------------------------------------- //
int guTVSoListBox::GetSelectedSongs( guTrackArray * tracks, const bool isdrag ) const
{
unsigned long cookie;
guTVSoListBox * self = wxConstCast( this, guTVSoListBox );
self->m_ItemsMutex.Lock();
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
tracks->Add( new guTrack( m_Items[ item ] ) );
item = GetNextSelected( cookie );
}
self->m_ItemsMutex.Unlock();
m_MediaViewer->NormalizeTracks( tracks, isdrag );
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
void guTVSoListBox::GetAllSongs( guTrackArray * tracks )
{
m_ItemsMutex.Lock();
int count = m_Items.Count();
for( int index = 0; index < count; index++ )
{
tracks->Add( new guTrack( m_Items[ index ] ) );
}
m_ItemsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
wxString guTVSoListBox::GetItemName( const int row ) const
{
return m_Items[ row ].m_SongName;
}
// -------------------------------------------------------------------------------- //
int guTVSoListBox::GetItemId( const int row ) const
{
return m_Items[ row ].m_SongId;
}
// -------------------------------------------------------------------------------- //
void guTVSoListBox::GetCounters( wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
m_Db->GetSongsCounters( m_Filters, m_TextFilters, count, len, size );
}
// -------------------------------------------------------------------------------- //
wxString guTVSoListBox::GetSearchText( int item ) const
{
return wxString::Format( wxT( "\"%s\" \"%s\"" ),
m_Items[ item ].m_ArtistName.c_str(),
m_Items[ item ].m_SongName.c_str() );
}
}
// -------------------------------------------------------------------------------- //
| 6,077
|
C++
|
.cpp
| 146
| 38.486301
| 110
| 0.562288
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,603
|
TreeViewFilter.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/treeview/TreeViewFilter.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TreeViewFilter.h"
#include <wx/arrimpl.cpp>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guTreeViewFilterEntry )
WX_DEFINE_OBJARRAY( guTreeViewFilterArray )
}
// -------------------------------------------------------------------------------- //
| 1,304
|
C++
|
.cpp
| 28
| 45.392857
| 86
| 0.5893
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,604
|
TreeViewFilterEditor.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/treeview/TreeViewFilterEditor.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TreeViewFilterEditor.h"
#include "Config.h"
#include "Images.h"
#include "Utils.h"
#include <wx/tokenzr.h>
namespace Guayadeque {
wxArrayString FilterItemNames;
// -------------------------------------------------------------------------------- //
guTreeViewFilterEditor::guTreeViewFilterEditor( wxWindow * parent, const wxString &filterentry ) :
wxDialog( parent, wxID_ANY, _( "Filter Editor" ), wxDefaultPosition, wxSize( 410, 310 ), wxDEFAULT_DIALOG_STYLE )
{
m_CurrentItem = wxNOT_FOUND;
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
MainSizer->Add( 0, 10, 0, wxEXPAND, 5 );
wxBoxSizer * NameSizer = new wxBoxSizer( wxHORIZONTAL );
wxStaticText * NameLabel = new wxStaticText( this, wxID_ANY, _( "Name:" ), wxDefaultPosition, wxDefaultSize, 0 );
NameLabel->Wrap( -1 );
NameSizer->Add( NameLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_NameTextCtrl = new wxTextCtrl( this, wxID_ANY, filterentry.BeforeFirst( wxT( ':' ) ), wxDefaultPosition, wxDefaultSize, 0 );
NameSizer->Add( m_NameTextCtrl, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 );
MainSizer->Add( NameSizer, 0, wxEXPAND, 5 );
wxStaticBoxSizer * FiltersSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _( "Filters" ) ), wxVERTICAL );
wxBoxSizer * FiltersListBoxSizer = new wxBoxSizer( wxHORIZONTAL );
if( !FilterItemNames.Count() )
{
FilterItemNames.Add( wxT( "Dummy" ) );
//FilterItemNames.Add( wxT( "Text" ) );
FilterItemNames.Add( _( "Labels" ) );
FilterItemNames.Add( _( "Genre" ) );
FilterItemNames.Add( _( "Artist" ) );
FilterItemNames.Add( _( "Composer" ) );
FilterItemNames.Add( _( "Album Artist" ) );
FilterItemNames.Add( _( "Album" ) );
FilterItemNames.Add( _( "Year" ) );
FilterItemNames.Add( _( "Rating" ) );
FilterItemNames.Add( _( "Play Count" ) );
}
wxArrayString FilterItems = wxStringTokenize( filterentry.AfterFirst( wxT( ':' ) ), wxT( ':' ) );
int Count = FilterItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
long Value;
FilterItems[ Index ].ToLong( &Value );
m_FilterItems.Add( Value );
}
}
m_FiltersListBox = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_SINGLE );
Count = m_FilterItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_FiltersListBox->Append( FilterItemNames[ m_FilterItems[ Index ] ] );
}
FiltersListBoxSizer->Add( m_FiltersListBox, 1, wxEXPAND|wxTOP|wxLEFT, 5 );
wxBoxSizer * FilterButtonsSizer = new wxBoxSizer( wxVERTICAL );
m_UpFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_up ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_UpFilterButton->Enable( false );
FilterButtonsSizer->Add( m_UpFilterButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5 );
m_DownFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_down ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DownFilterButton->Enable( false );
FilterButtonsSizer->Add( m_DownFilterButton, 0, wxALIGN_CENTER_HORIZONTAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_DelFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_del ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DelFilterButton->Enable( false );
FilterButtonsSizer->Add( m_DelFilterButton, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
FiltersListBoxSizer->Add( FilterButtonsSizer, 0, wxEXPAND, 5 );
FiltersSizer->Add( FiltersListBoxSizer, 1, wxEXPAND, 5 );
wxBoxSizer * NewFilterSizer = new wxBoxSizer( wxHORIZONTAL );
NewFilterSizer->Add( 0, 0, 1, wxEXPAND, 5 );
wxStaticText * NewFilterLabel = new wxStaticText( this, wxID_ANY, _( "Filter:" ), wxDefaultPosition, wxDefaultSize, 0 );
NewFilterLabel->Wrap( -1 );
NewFilterSizer->Add( NewFilterLabel, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT|wxLEFT, 5 );
wxString m_FiltersChoiceChoices[] = { _( "Genres" ), _( "Artist" ), _( "Composer" ), _( "Album Artist" ), _( "Album" ), _( "Year" ), _( "Rating" ), _( "PlayCount" ) };
int m_FiltersChoiceNChoices = sizeof( m_FiltersChoiceChoices ) / sizeof( wxString );
m_FiltersChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FiltersChoiceNChoices, m_FiltersChoiceChoices, 0 );
m_FiltersChoice->SetSelection( 0 );
NewFilterSizer->Add( m_FiltersChoice, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT, 5 );
m_AddFilterButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_add ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
NewFilterSizer->Add( m_AddFilterButton, 0, wxTOP|wxRIGHT, 5 );
FiltersSizer->Add( NewFilterSizer, 0, wxEXPAND, 5 );
MainSizer->Add( FiltersSizer, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStdDialogButtonSizer * ButtonsSizer = new wxStdDialogButtonSizer();
m_AcceptButton = new wxButton( this, wxID_OK );
m_AcceptButton->Enable( !m_NameTextCtrl->IsEmpty() && m_FiltersListBox->GetCount() );
ButtonsSizer->AddButton( m_AcceptButton );
wxButton * ButtonsSizerCancel = new wxButton( this, wxID_CANCEL );
ButtonsSizer->AddButton( ButtonsSizerCancel );
ButtonsSizer->SetAffirmativeButton( m_AcceptButton );
ButtonsSizer->SetCancelButton( ButtonsSizerCancel );
ButtonsSizer->Realize();
MainSizer->Add( ButtonsSizer, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
m_AcceptButton->SetDefault();
// Bind Events
m_NameTextCtrl->Bind( wxEVT_TEXT, &guTreeViewFilterEditor::OnCheckAcceptButton, this );
m_FiltersListBox->Bind( wxEVT_LISTBOX, &guTreeViewFilterEditor::OnFilterListBoxSelected, this );
m_UpFilterButton->Bind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnUpFilterBtnClick, this );
m_DownFilterButton->Bind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnDownFilterBtnClick, this );
m_DelFilterButton->Bind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnDelFilterBtnClick, this );
m_AddFilterButton->Bind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnAddFilterBtnClick, this );
m_NameTextCtrl->SetFocus();
}
// -------------------------------------------------------------------------------- //
guTreeViewFilterEditor::~guTreeViewFilterEditor()
{
m_NameTextCtrl->Unbind( wxEVT_TEXT, &guTreeViewFilterEditor::OnCheckAcceptButton, this );
m_FiltersListBox->Unbind( wxEVT_LISTBOX, &guTreeViewFilterEditor::OnFilterListBoxSelected, this );
m_UpFilterButton->Unbind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnUpFilterBtnClick, this );
m_DownFilterButton->Unbind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnDownFilterBtnClick, this );
m_DelFilterButton->Unbind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnDelFilterBtnClick, this );
m_AddFilterButton->Unbind( wxEVT_BUTTON, &guTreeViewFilterEditor::OnAddFilterBtnClick, this );
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnFilterListBoxSelected( wxCommandEvent& event )
{
m_CurrentItem = event.GetInt();
if( m_CurrentItem != wxNOT_FOUND )
{
m_UpFilterButton->Enable( m_CurrentItem > 0 );
m_DownFilterButton->Enable( m_CurrentItem < ( int ) ( m_FiltersListBox->GetCount() - 1 ) );
m_DelFilterButton->Enable( true );
}
else
{
m_UpFilterButton->Enable( false );
m_DownFilterButton->Enable( false );
m_DelFilterButton->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnUpFilterBtnClick( wxCommandEvent& event )
{
wxString OldItemStr = m_FiltersListBox->GetString( m_CurrentItem );
int OldItemVal = m_FilterItems[ m_CurrentItem ];
m_FiltersListBox->SetString( m_CurrentItem, m_FiltersListBox->GetString( m_CurrentItem - 1 ) );
m_FilterItems[ m_CurrentItem ] = m_FilterItems[ m_CurrentItem - 1 ];
m_CurrentItem--;
m_FiltersListBox->SetString( m_CurrentItem, OldItemStr );
m_FilterItems[ m_CurrentItem ] = OldItemVal;
m_FiltersListBox->SetSelection( m_CurrentItem );
event.SetInt( m_CurrentItem );
OnFilterListBoxSelected( event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnDownFilterBtnClick( wxCommandEvent& event )
{
wxString OldItemStr = m_FiltersListBox->GetString( m_CurrentItem );
int OldItemVal = m_FilterItems[ m_CurrentItem ];
m_FiltersListBox->SetString( m_CurrentItem, m_FiltersListBox->GetString( m_CurrentItem + 1 ) );
m_FilterItems[ m_CurrentItem ] = m_FilterItems[ m_CurrentItem + 1 ];
m_CurrentItem++;
m_FiltersListBox->SetString( m_CurrentItem, OldItemStr );
m_FilterItems[ m_CurrentItem ] = OldItemVal;
m_FiltersListBox->SetSelection( m_CurrentItem );
event.SetInt( m_CurrentItem );
OnFilterListBoxSelected( event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnDelFilterBtnClick( wxCommandEvent& event )
{
m_FilterItems.RemoveAt( m_CurrentItem );
m_FiltersListBox->Delete( m_CurrentItem );
OnCheckAcceptButton( event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnAddFilterBtnClick( wxCommandEvent& event )
{
int SelectedItem = m_FiltersChoice->GetCurrentSelection() + 2;
if( m_FilterItems.Index( SelectedItem ) == wxNOT_FOUND )
{
m_FilterItems.Add( SelectedItem );
m_FiltersListBox->Append( FilterItemNames[ SelectedItem ] );
OnCheckAcceptButton( event );
}
}
// -------------------------------------------------------------------------------- //
wxString guTreeViewFilterEditor::GetTreeViewFilterEntry( void )
{
wxString RetVal = m_NameTextCtrl->GetValue();
int Count = m_FilterItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
RetVal += wxString::Format( wxT( ":%i" ), m_FilterItems[ Index ] );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guTreeViewFilterEditor::OnCheckAcceptButton( wxCommandEvent &event )
{
m_AcceptButton->Enable( !event.GetString().IsEmpty() && m_FiltersListBox->GetCount() );
}
}
// -------------------------------------------------------------------------------- //
| 11,515
|
C++
|
.cpp
| 216
| 49.527778
| 168
| 0.657448
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,605
|
TreePanel.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/treeview/TreePanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TreePanel.h"
#include "Accelerators.h"
#include "AuiNotebook.h"
#include "AuiDockArt.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "DbLibrary.h"
#include "DynamicPlayList.h"
#include "EditWithOptions.h"
#include "FileRenamer.h"
#include "Images.h"
#include "LabelEditor.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "OnlineLinks.h"
#include "PlayListAppend.h"
#include "PlayListFile.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "TreeViewFilterEditor.h"
#include "Utils.h"
#include <wx/tokenzr.h>
namespace Guayadeque {
//#define guTREEVIEW_TIMER_TEXTSEARCH 5
//#define guTREEVIEW_TIMER_TEXTSEARCH_VALUE 500
#define guTREEVIEW_TIMER_TREEITEMSELECTED 6
#define guTREEVIEW_TIMER_TREEITEMSELECTED_VALUE 50
BEGIN_EVENT_TABLE( guTreeViewTreeCtrl, wxTreeCtrl )
EVT_TREE_BEGIN_DRAG( wxID_ANY, guTreeViewTreeCtrl::OnBeginDrag )
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guTreeViewTreeCtrl::guTreeViewTreeCtrl( wxWindow * parent, guDbLibrary * db, guTreeViewPanel * treeviewpanel ) :
wxTreeCtrl( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_FULL_ROW_HIGHLIGHT|wxTR_MULTIPLE|wxTR_TWIST_BUTTONS|wxNO_BORDER )
{
m_Db = db;
m_TreeViewPanel = treeviewpanel;
m_ConfigPath = treeviewpanel->ConfigPath();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_FilterEntries = Config->ReadAStr( wxT( "Filter" ), wxEmptyString, m_ConfigPath + wxT( "/sortings" ) );
m_CurrentFilter = Config->ReadNum( wxT( "TreeViewFilter" ), 0, m_ConfigPath );
if( !m_FilterEntries.Count() )
{
m_FilterEntries.Add( wxString( _( "Genres,Artists,Albums" ) ) + wxT( ":2:3:6") );
m_FilterEntries.Add( wxString( _( "Genres,Year,Artists,Albums" ) ) + wxT( ":2:7:3:6") );
m_CurrentFilter = 0;
}
if( ( m_CurrentFilter < 0 ) || ( m_CurrentFilter >= ( int ) m_FilterEntries.Count() ) )
{
m_CurrentFilter = 0;
}
m_ImageList = new wxImageList();
m_ImageList->Add( wxBitmap( guImage( guIMAGE_INDEX_track ) ) );
m_ImageList->Add( wxBitmap( guImage( guIMAGE_INDEX_filter ) ) );
AssignImageList( m_ImageList );
m_RootId = AddRoot( wxT( "Sortings" ), -1, -1, NULL );
m_FiltersId = AppendItem( m_RootId, _( "Sortings" ), 1, 1, NULL );
m_LibraryId = AppendItem( m_RootId, _( "Library" ), 0, 0, NULL );
SetIndent( 10 );
Bind( wxEVT_MENU, &guTreeViewTreeCtrl::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_TREE_ITEM_MENU, &guTreeViewTreeCtrl::OnContextMenu, this );
Bind( wxEVT_MENU, &guTreeViewTreeCtrl::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Bind( guConfigUpdatedEvent, &guTreeViewTreeCtrl::OnConfigUpdated, this, ID_CONFIG_UPDATED );
CreateAcceleratorTable();
LoadFilterLayout();
ReloadFilters();
ReloadItems();
Expand( m_FiltersId );
Expand( m_LibraryId );
}
// -------------------------------------------------------------------------------- //
guTreeViewTreeCtrl::~guTreeViewTreeCtrl()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteAStr( wxT( "Filter" ), m_FilterEntries, m_ConfigPath + wxT( "/sortings" ) );
Config->WriteNum( wxT( "TreeViewFilter" ), m_CurrentFilter, m_ConfigPath );
Unbind( wxEVT_MENU, &guTreeViewTreeCtrl::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_TREE_ITEM_MENU, &guTreeViewTreeCtrl::OnContextMenu, this );
Unbind( wxEVT_MENU, &guTreeViewTreeCtrl::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Unbind( guConfigUpdatedEvent, &guTreeViewTreeCtrl::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_TREEVIEW_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_TREEVIEW_EDITLABELS );
RealAccelCmds.Add( ID_TREEVIEW_EDITTRACKS );
RealAccelCmds.Add( ID_TREEVIEW_PLAY );
RealAccelCmds.Add( ID_TREEVIEW_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_TREEVIEW_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_TREEVIEW_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_TREEVIEW_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_TREEVIEW_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
wxTreeItemId LastTreeItemId[ 10 ];
// -------------------------------------------------------------------------------- //
void AddTreeItems( wxTreeCtrl * treectrl, wxTreeItemId &curitem, wxSQLite3ResultSet &dbres, const wxArrayInt &filters, wxArrayInt &lastdata, const int curfilter, const int respos )
{
//guLogMessage( wxT( "%02i %02i %02i (%02i)" ), curfilter, filters[ curfilter ], respos, lastdata[ curfilter ] );
if( lastdata[ curfilter ] != dbres.GetInt( respos ) )
{
lastdata[ curfilter ] = dbres.GetInt( respos );
for( int Index = curfilter + 1; Index < ( int ) filters.Count(); Index++ )
lastdata[ Index ] = wxNOT_FOUND;
LastTreeItemId[ curfilter ] = treectrl->AppendItem( curitem,
( filters[ curfilter ] < guLIBRARY_ELEMENT_YEARS ) ? dbres.GetString( respos + 1 ) : wxString::Format( wxT( "%i" ), lastdata[ curfilter ] ),
wxNOT_FOUND,
wxNOT_FOUND,
new guTreeViewData( lastdata[ curfilter ], filters[ curfilter ] ) );
}
if( curfilter < ( int ) filters.Count() - 1 )
{
AddTreeItems( treectrl, LastTreeItemId[ curfilter ], dbres, filters, lastdata, curfilter + 1, respos + ( ( filters[ curfilter ] < guLIBRARY_ELEMENT_YEARS ) ? 2 : 1 ) );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::LoadFilterLayout( void )
{
m_FilterLayout.Empty();
wxArrayString FilterItems = wxStringTokenize( m_FilterEntries[ m_CurrentFilter ].AfterFirst( wxT( ':' ) ), wxT( ':' ) );
int Count = FilterItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
long Value;
FilterItems[ Index ].ToLong( &Value );
m_FilterLayout.Add( Value );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::ReloadFilters( void )
{
DeleteChildren( m_FiltersId );
wxFont BoldFont = GetFont();
BoldFont.SetWeight( wxFONTWEIGHT_BOLD );
int Count = m_FilterEntries.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxTreeItemId CurItem = AppendItem( m_FiltersId, m_FilterEntries[ Index ].BeforeFirst( wxT( ':' ) ), wxNOT_FOUND, wxNOT_FOUND,
new guTreeViewData( Index, Index ) );
if( Index == m_CurrentFilter )
SetItemFont( CurItem, BoldFont );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::ReloadItems( void )
{
DeleteChildren( m_LibraryId );
wxArrayInt LastDataIds;
LastDataIds.Add( wxNOT_FOUND, m_FilterLayout.Count() );
wxString Query = wxT( "SELECT DISTINCT " );
wxString Sorting = wxT( " ORDER BY " );
int Count = m_FilterLayout.Count();
for( int Index = 0; Index < Count; Index++ )
{
switch( m_FilterLayout[ Index ] )
{
case guLIBRARY_ELEMENT_GENRES :
Query += wxT( "song_genreid, song_genre" );
Sorting += wxT( "song_genre" );
break;
case guLIBRARY_ELEMENT_ARTISTS :
Query += wxT( "song_artistid, song_artist" );
Sorting += wxT( "song_artist" );
break;
case guLIBRARY_ELEMENT_COMPOSERS :
Query += wxT( "song_composerid, song_composer" );
Sorting += wxT( "song_composer" );
break;
case guLIBRARY_ELEMENT_ALBUMARTISTS :
Query += wxT( "song_albumartistid, song_albumartist" );
Sorting += wxT( "song_albumartist" );
break;
case guLIBRARY_ELEMENT_ALBUMS :
Query += wxT( "song_albumid, song_album" );
Sorting += wxT( "song_album" );
break;
case guLIBRARY_ELEMENT_YEARS :
Query += wxT( "song_year" );
Sorting += wxT( "song_year DESC" );
break;
case guLIBRARY_ELEMENT_RATINGS :
Query += wxT( "song_rating" );
Sorting += wxT( "song_rating DESC" );
break;
case guLIBRARY_ELEMENT_PLAYCOUNT :
Query += wxT( "song_playcount" );
Sorting += wxT( "song_playcount DESC" );
break;
}
Query += wxT( ", " );
Sorting += wxT( ", " );
}
Query.RemoveLast( 2 );
Sorting.RemoveLast( 2 );
Query += wxT( " FROM songs " );
if( m_TextFilters.Count() )
{
Query += wxT( "WHERE " ) + TextFilterToSQL( m_TextFilters );
}
wxSQLite3ResultSet dbRes;
dbRes = m_Db->ExecuteQuery( Query + Sorting );
while( dbRes.NextRow() )
{
AddTreeItems( this, m_LibraryId, dbRes, m_FilterLayout, LastDataIds, 0, 0 );
}
dbRes.Finalize();
}
// -------------------------------------------------------------------------------- //
void AddTreeViewCommands( wxMenu * Menu, int ItemType )
{
if( Menu && ( ( ItemType == guLIBRARY_ELEMENT_ARTISTS ) ||
( ItemType == guLIBRARY_ELEMENT_ALBUMARTISTS ) ||
( ItemType == guLIBRARY_ELEMENT_ALBUMS ) ) )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem = NULL;
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( ItemType == guLIBRARY_ELEMENT_ALBUMS ) ||
( ItemType == guLIBRARY_ELEMENT_ARTISTS ) ||
( ItemType == guLIBRARY_ELEMENT_ALBUMARTISTS ) )
{
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
}
SubMenu->Append( MenuItem );
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::OnContextMenu( wxTreeEvent &event )
{
wxMenu Menu;
wxMenuItem * MenuItem;
wxPoint Point = event.GetPoint();
wxArrayTreeItemIds SelectedItems;
int SelectCount = GetSelections( SelectedItems );
wxTreeItemId ItemId = event.GetItem();
guTreeViewData * ItemData = NULL;
if( ItemId.IsOk() )
{
if( ItemId == m_FiltersId || GetItemParent( ItemId ) == m_FiltersId )
{
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_FILTER_NEW, _( "Create" ), _( "Create a new filter" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_FILTER_EDIT, _( "Edit" ), _( "Edit the selected filter" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_FILTER_DELETE, _( "Delete" ), _( "Delete the selected filter" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu.Append( MenuItem );
Menu.AppendSeparator();
}
else
{
ItemData = ( guTreeViewData * ) GetItemData( ItemId );
if( ItemData )
{
int ContextMenuFlags = GetContextMenuFlags();
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_PLAY, _( "Play" ), _( "Play current selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected songs to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_add ) );
Menu.Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_TREEVIEW_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_TREEVIEW_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_TREEVIEW_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu.Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu.AppendSeparator();
int ItemType = ItemData->m_Type;
//guLogMessage( wxT( "SelCount: %i Type: %i" ), SelectCount, ItemType );
if( SelectCount == 1 )
{
if( ItemType == guLIBRARY_ELEMENT_ARTISTS ||
ItemType == guLIBRARY_ELEMENT_ALBUMS )
{
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_EDITLABELS,
wxString( _( "Edit Labels" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITLABELS ),
_( "Edit the labels assigned to the selected items" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu.Append( MenuItem );
}
}
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu.Append( MenuItem );
}
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_TREEVIEW_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu.Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ( SelectCount == 1 ) && ContextMenuFlags & ( guCONTEXTMENU_LINKS | guCONTEXTMENU_COMMANDS ) ) )
{
Menu.AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
m_TreeViewPanel->CreateCopyToMenu( &Menu );
}
if( SelectCount == 1 )
{
if( ItemType == guLIBRARY_ELEMENT_ARTISTS ||
ItemType == guLIBRARY_ELEMENT_ALBUMARTISTS ||
ItemType == guLIBRARY_ELEMENT_ALBUMS )
{
if( ContextMenuFlags & guCONTEXTMENU_LINKS )
{
AddOnlineLinksMenu( &Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
{
AddTreeViewCommands( &Menu, ItemType );
}
}
}
}
m_TreeViewPanel->CreateContextMenu( &Menu, ItemType );
}
else
{
return;
}
}
}
PopupMenu( &Menu, Point );
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::OnBeginDrag( wxTreeEvent &event )
{
wxArrayTreeItemIds SelectedItems;
if( GetSelections( SelectedItems ) )
{
guTrackArray Tracks;
m_TreeViewPanel->GetAllTracks( &Tracks );
int Count = Tracks.Count();
if( Count )
{
wxFileDataObject Files;
for( int Index = 0; Index < Count; Index++ )
{
Files.AddFile( Tracks[ Index ].m_FileName );
}
wxDropSource source( Files, this );
wxDragResult Result = source.DoDragDrop();
if( Result )
{
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::GetItemFilterEntry( const wxTreeItemId &treeitemid, guTreeViewFilterEntry &filterentry )
{
wxTreeItemId CurItemId = treeitemid;
if( treeitemid == m_FiltersId || GetItemParent( treeitemid ) == m_FiltersId )
return;
while( CurItemId.IsOk() )
{
guTreeViewData * TreeViewData = ( guTreeViewData * ) GetItemData( CurItemId );
if( TreeViewData )
{
filterentry.Add( new guTreeViewFilterItem( TreeViewData->m_Type, TreeViewData->m_Id ) );
}
else
{
return;
}
CurItemId = GetItemParent( CurItemId );
if( IsSelected( CurItemId ) )
{
filterentry.Empty();
return;
}
}
}
// -------------------------------------------------------------------------------- //
bool guTreeViewTreeCtrl::IsFilterItem( const wxTreeItemId &treeitemid )
{
wxTreeItemId CurItemId = treeitemid;
while( CurItemId.IsOk() )
{
if( CurItemId == m_LibraryId || GetItemParent( CurItemId ) == m_LibraryId )
return true;
CurItemId = GetItemParent( CurItemId );
}
return false;
}
// -------------------------------------------------------------------------------- //
wxArrayString GetSelectedAlbumPaths( guDbLibrary * db, const int id, const int type )
{
wxArrayString RetVal;
wxArrayInt SelectedItems;
SelectedItems.Add( id );
switch( type )
{
case guLIBRARY_ELEMENT_ARTISTS :
{
wxArrayInt AlbumList;
db->GetArtistsAlbums( SelectedItems, &AlbumList );
RetVal = db->GetAlbumsPaths( AlbumList );
break;
}
case guLIBRARY_ELEMENT_ALBUMS :
{
RetVal = db->GetAlbumsPaths( SelectedItems );
break;
}
case guLIBRARY_ELEMENT_ALBUMARTISTS :
{
wxArrayInt AlbumList;
db->GetAlbumArtistsAlbums( SelectedItems, &AlbumList );
RetVal = db->GetAlbumsPaths( AlbumList );
break;
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int GetSelectedCoverId( guDbLibrary * db, const int id, const int type )
{
int RetVal = 0;
wxArrayInt SelectedItems;
SelectedItems.Add( id );
switch( type )
{
case guLIBRARY_ELEMENT_ARTISTS :
{
wxArrayInt AlbumList;
db->GetArtistsAlbums( SelectedItems, &AlbumList );
RetVal = db->GetAlbumCoverId( AlbumList[ 0 ] );
break;
}
case guLIBRARY_ELEMENT_ALBUMS :
{
RetVal = db->GetAlbumCoverId( id );
break;
}
case guLIBRARY_ELEMENT_ALBUMARTISTS :
{
wxArrayInt AlbumList;
db->GetAlbumArtistsAlbums( SelectedItems, &AlbumList );
RetVal = db->GetAlbumCoverId( AlbumList[ 0 ] );
break;
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
int GetSelectedTracks( guDbLibrary * db, guTrackArray * tracks, const int id, const int type )
{
wxArrayInt SelectedItems;
SelectedItems.Add( id );
switch( type )
{
case guLIBRARY_ELEMENT_ARTISTS :
{
return db->GetArtistsSongs( SelectedItems, tracks );
}
case guLIBRARY_ELEMENT_ALBUMS :
{
return db->GetAlbumsSongs( SelectedItems, tracks );
}
case guLIBRARY_ELEMENT_ALBUMARTISTS :
{
return db->GetAlbumArtistsSongs( SelectedItems, tracks );
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
wxString GetAlbumSearchText( guDbLibrary * db, const int id, const int type )
{
wxString Query;
wxSQLite3ResultSet dbRes;
wxString RetVal;
Query = wxString::Format( wxT( "SELECT song_artist, song_album FROM songs WHERE song_albumid = %i LIMIT 1" ), id );
dbRes = db->ExecuteQuery( Query );
if( dbRes.NextRow() )
{
RetVal = wxString::Format( wxT( "\"%s\" \"%s\"" ),
dbRes.GetString( 0 ).c_str(),
dbRes.GetString( 1 ).c_str() );
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::OnSearchLinkClicked( wxCommandEvent &event )
{
const wxTreeItemId &CurItemId = GetFocusedItem();
guTreeViewData * TreeViewData = ( guTreeViewData * ) GetItemData( CurItemId );
int ItemType = TreeViewData->GetType();
if( ItemType == guLIBRARY_ELEMENT_ALBUMS )
{
ExecuteOnlineLink( event.GetId(), GetAlbumSearchText( m_Db, TreeViewData->GetData(), TreeViewData->GetType() ) );
}
else
{
ExecuteOnlineLink( event.GetId(), GetItemText( CurItemId ) );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewTreeCtrl::OnCommandClicked( wxCommandEvent &event )
{
const wxTreeItemId &CurItemId = GetFocusedItem();
guTreeViewData * TreeViewData = ( guTreeViewData * ) GetItemData( CurItemId );
// int ItemType = TreeViewData->GetType();
wxArrayInt Selection;
Selection.Add( TreeViewData->GetData() );
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
//guLogMessage( wxT( "CommandId: %u" ), Index );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayString AlbumPaths = GetSelectedAlbumPaths( m_Db, TreeViewData->GetData(), TreeViewData->GetType() );
int Count = AlbumPaths.Count();
wxString Paths = wxEmptyString;
for( int Index = 0; Index < Count; Index++ )
{
AlbumPaths[ Index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ Index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
int CoverId = GetSelectedCoverId( m_Db, TreeViewData->GetData(), TreeViewData->GetType() );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
wxString SongList = wxEmptyString;
if( GetSelectedTracks( m_Db, &Songs, TreeViewData->GetData(), TreeViewData->GetType() ) )
{
int Count = Songs.Count();
for( int Index = 0; Index < Count; Index++ )
{
SongList += wxT( " \"" ) + Songs[ Index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
// -------------------------------------------------------------------------------- //
int guTreeViewTreeCtrl::GetContextMenuFlags( void )
{
return m_TreeViewPanel->GetContextMenuFlags();
}
// -------------------------------------------------------------------------------- //
// guTreeViewPanel
// -------------------------------------------------------------------------------- //
guTreeViewPanel::guTreeViewPanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guAuiManagerPanel( parent ),
//m_TextChangedTimer( this, guTREEVIEW_TIMER_TEXTSEARCH ),
m_TreeItemSelectedTimer( this, guTREEVIEW_TIMER_TREEITEMSELECTED )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_PlayerPanel = mediaviewer->GetPlayerPanel();
m_ConfigPath = m_MediaViewer->ConfigPath() + wxT( "/treeview" );
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_VisiblePanels = Config->ReadNum( wxT( "VisiblePanels" ), guPANEL_PLAYLIST_VISIBLE_DEFAULT, m_ConfigPath );
InitPanelData();
CreateControls();
}
// -------------------------------------------------------------------------------- //
guTreeViewPanel::~guTreeViewPanel()
{
// Save the Splitter positions into the main config
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteNum( wxT( "VisiblePanels" ), m_VisiblePanels, m_ConfigPath );
Config->WriteStr( wxT( "LastLayout" ), m_AuiManager.SavePerspective(), m_ConfigPath );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::CreateControls( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPanel * NamesPanel;
NamesPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * NameSizer;
NameSizer = new wxBoxSizer( wxVERTICAL );
m_TreeViewCtrl = new guTreeViewTreeCtrl( NamesPanel, m_Db, this );
//m_TreeViewCtrl->ExpandAll();
NameSizer->Add( m_TreeViewCtrl, 1, wxEXPAND, 5 );
NamesPanel->SetSizer( NameSizer );
NamesPanel->Layout();
NameSizer->Fit( NamesPanel );
m_AuiManager.AddPane( NamesPanel,
wxAuiPaneInfo().Name( wxT( "TreeViewFilters" ) ).Caption( _( "Tree" ) ).
MinSize( 50, 50 ).CloseButton( false ).
Dockable( true ).Left() );
wxPanel * DetailsPanel;
DetailsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * DetailsSizer;
DetailsSizer = new wxBoxSizer( wxVERTICAL );
m_TVTracksListBox = new guTVSoListBox( DetailsPanel, m_MediaViewer, m_ConfigPath, guLISTVIEW_COLUMN_SELECT|guLISTVIEW_COLUMN_SORTING );
DetailsSizer->Add( m_TVTracksListBox, 1, wxEXPAND, 5 );
DetailsPanel->SetSizer( DetailsSizer );
DetailsPanel->Layout();
DetailsSizer->Fit( DetailsPanel );
m_AuiManager.AddPane( DetailsPanel, wxAuiPaneInfo().Name( wxT( "TreeViewTracks" ) ).Caption( wxT( "TreeView" ) ).
MinSize( 50, 50 ).
CenterPane() );
wxString TreeViewLayout = Config->ReadStr( wxT( "LastLayout" ), wxEmptyString, m_ConfigPath );
if( Config->GetIgnoreLayouts() || TreeViewLayout.IsEmpty() )
{
m_VisiblePanels = guPANEL_TREEVIEW_VISIBLE_DEFAULT;
TreeViewLayout = wxT( "layout2|name=TreeViewFilters;caption=" ) + wxString( _( "Tree" ) );
TreeViewLayout += wxT( ";state=2044;dir=4;layer=0;row=0;pos=0;prop=100000;bestw=180;besth=350;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
TreeViewLayout += wxT( "name=TreeViewTracks;caption=PlayList;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
TreeViewLayout += wxT( "dock_size(1,2,0)=47|dock_size(4,0,0)=186|dock_size(5,0,0)=52|" );
}
m_AuiManager.LoadPerspective( TreeViewLayout, true );
Bind( wxEVT_TREE_SEL_CHANGED, &guTreeViewPanel::OnTreeViewSelected, this );
Bind( wxEVT_TREE_ITEM_ACTIVATED, &guTreeViewPanel::OnTreeViewActivated, this );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewNewFilter, this, ID_TREEVIEW_FILTER_NEW );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewEditFilter, this, ID_TREEVIEW_FILTER_EDIT );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewDeleteFilter, this, ID_TREEVIEW_FILTER_DELETE );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewPlay, this, ID_TREEVIEW_PLAY );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewEnqueue, this, ID_TREEVIEW_ENQUEUE_AFTER_ALL, ID_TREEVIEW_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewEditLabels, this, ID_TREEVIEW_EDITLABELS );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewEditTracks, this, ID_TREEVIEW_EDITTRACKS );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewSaveToPlayList, this, ID_TREEVIEW_SAVETOPLAYLIST );
m_TreeViewCtrl->Bind( wxEVT_MENU, &guTreeViewPanel::OnTreeViewCopyTo, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
m_TVTracksListBox->Bind( wxEVT_LIST_COL_CLICK, &guTreeViewPanel::OnTrackListColClicked, this );
m_TVTracksListBox->Bind( wxEVT_LISTBOX_DCLICK, &guTreeViewPanel::OnTVTracksActivated, this );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksDeleteLibrary, this, ID_TRACKS_DELETE_LIBRARY );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksDeleteDrive, this, ID_TRACKS_DELETE_DRIVE );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksPlayClicked, this, ID_TRACKS_PLAY );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSetRating, this, ID_TRACKS_ENQUEUE_AFTER_ALL, ID_TRACKS_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksEditLabelsClicked, this, ID_TRACKS_EDITLABELS );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksEditTracksClicked, this, ID_TRACKS_EDITTRACKS );
m_TVTracksListBox->Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSavePlayListClicked, this, ID_TRACKS_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSetRating, this, ID_TRACKS_SET_RATING_0, ID_TRACKS_SET_RATING_5 );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSetField, this, ID_TRACKS_SET_COLUMN );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksEditField, this, ID_TRACKS_EDIT_COLUMN );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSelectGenre, this, ID_TRACKS_BROWSE_GENRE );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSelectArtist, this, ID_TRACKS_BROWSE_ARTIST );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSelectAlbumArtist, this, ID_TRACKS_BROWSE_ALBUMARTIST );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSelectComposer, this, ID_TRACKS_BROWSE_COMPOSER );
Bind( wxEVT_MENU, &guTreeViewPanel::OnTVTracksSelectAlbum, this, ID_TRACKS_BROWSE_ALBUM );
Bind( wxEVT_TIMER, &guTreeViewPanel::OnTreeItemSelectedTimer , this, guTREEVIEW_TIMER_TREEITEMSELECTED );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::InitPanelData()
{
}
// -------------------------------------------------------------------------------- //
int guTreeViewPanel::GetContextMenuFlags( void )
{
return m_MediaViewer->GetContextMenuFlags();
}
// -------------------------------------------------------------------------------- //
bool guTreeViewPanel::DoTextSearch( const wxString &textsearch )
{
if( m_LastSearchString != textsearch )
{
m_LastSearchString = textsearch; //m_InputTextCtrl->GetValue();
if( !m_LastSearchString.IsEmpty() )
{
if( m_LastSearchString.Length() > 0 )
{
wxArrayString TextFilters = guSplitWords( m_LastSearchString );
m_TreeViewCtrl->SetTextFilters( TextFilters );
// m_TreeViewCtrl->ExpandAll();
m_TreeViewCtrl->ReloadItems();
m_TVTracksListBox->SetTextFilters( TextFilters );
m_TVTracksListBox->ReloadItems( false );
}
// m_InputTextCtrl->ShowCancelButton( true );
return true;
}
else
{
m_TreeViewCtrl->ClearTextFilters();
// m_TreeViewCtrl->ExpandAll();
m_TreeViewCtrl->ReloadItems();
m_TVTracksListBox->ClearTextFilters();
m_TVTracksListBox->ReloadItems( false );
// m_InputTextCtrl->ShowCancelButton( false );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeItemSelectedTimer( wxTimerEvent &event )
{
guTreeViewFilterArray FilterArray;
wxArrayTreeItemIds Selections;
if( m_TreeViewCtrl->GetSelections( Selections ) )
{
int Count = Selections.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTreeViewFilterEntry FilterEntry;
m_TreeViewCtrl->GetItemFilterEntry( Selections[ Index ], FilterEntry );
if( FilterEntry.Count() )
{
FilterArray.Add( FilterEntry );
}
}
}
m_TVTracksListBox->SetFilters( FilterArray );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewSelected( wxTreeEvent& event )
{
if( m_TreeItemSelectedTimer.IsRunning() )
m_TreeItemSelectedTimer.Stop();
m_TreeItemSelectedTimer.Start( guTREEVIEW_TIMER_TREEITEMSELECTED_VALUE, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewActivated( wxTreeEvent& event )
{
const wxTreeItemId &CurItemId = event.GetItem();
if( m_TreeViewCtrl->IsFilterEntry( CurItemId ) )
{
guTreeViewData * ItemData = ( guTreeViewData * ) m_TreeViewCtrl->GetItemData( CurItemId );
if( ItemData )
{
m_TreeViewCtrl->SetCurrentFilter( ItemData->GetData() );
m_TreeViewCtrl->ReloadItems();
return;
}
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewPlay( wxCommandEvent &event )
{
if( m_TreeViewCtrl->IsFilterItem( m_TreeViewCtrl->GetFocusedItem() ) )
{
guTrackArray Tracks;
m_TVTracksListBox->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
m_PlayerPanel->SetPlayList( Tracks );
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewEnqueue( wxCommandEvent &event )
{
if( m_TreeViewCtrl->IsFilterItem( m_TreeViewCtrl->GetFocusedItem() ) )
{
guTrackArray Tracks;
m_TVTracksListBox->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
m_PlayerPanel->AddToPlayList( Tracks, true, event.GetId() - ID_TREEVIEW_ENQUEUE_AFTER_ALL );
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewEditLabels( wxCommandEvent &event )
{
const wxTreeItemId &CurItemId = m_TreeViewCtrl->GetFocusedItem();
if( m_TreeViewCtrl->IsFilterItem( CurItemId ) )
{
guTreeViewData * ItemData = ( guTreeViewData * ) m_TreeViewCtrl->GetItemData( CurItemId );
if( ItemData )
{
if( ( ItemData->GetType() == guLIBRARY_ELEMENT_ARTISTS ) ||
( ItemData->GetType() == guLIBRARY_ELEMENT_ALBUMS ) )
{
guArrayListItems LabelSets;
wxArrayInt IdList;
IdList.Add( ItemData->GetData() );
int ItemType = ItemData->GetType();
if( ItemType == guLIBRARY_ELEMENT_ARTISTS )
{
LabelSets = m_Db->GetArtistsLabels( IdList );
}
else if( ItemType == guLIBRARY_ELEMENT_ALBUMS )
{
LabelSets = m_Db->GetAlbumsLabels( IdList );
}
guListItems ListItems;
ListItems.Add( new guListItem( ItemData->GetData(), m_TreeViewCtrl->GetItemText( CurItemId ) ) );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db,
ItemType == guLIBRARY_ELEMENT_ARTISTS ? _( "Artist Labels Editor" ) : _( "Albums Labels Editor" ),
false, &ListItems, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the artists files
if( ItemType == guLIBRARY_ELEMENT_ARTISTS )
{
m_Db->UpdateArtistsLabels( LabelSets );
}
else
{
m_Db->UpdateAlbumsLabels( LabelSets );
}
}
LabelEditor->Destroy();
wxCommandEvent event( wxEVT_MENU, ID_LABEL_UPDATELABELS );
wxPostEvent( m_MediaViewer, event );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewEditTracks( wxCommandEvent &event )
{
const wxTreeItemId &CurItemId = m_TreeViewCtrl->GetFocusedItem();
if( CurItemId.IsOk() && m_TreeViewCtrl->IsFilterItem( CurItemId ) )
{
guTrackArray Tracks;
m_TVTracksListBox->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Tracks, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
//guUpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
//m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
m_TVTracksListBox->ReloadItems();
// Update the track in database, playlist, etc
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewSaveToPlayList( wxCommandEvent &event )
{
const wxTreeItemId &CurItemId = m_TreeViewCtrl->GetFocusedItem();
if( m_TreeViewCtrl->IsFilterItem( CurItemId ) )
{
guTrackArray Tracks;
m_TVTracksListBox->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
wxArrayInt NewSongs;
//NormalizeTracks( &Tracks );
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
NewSongs.Add( Tracks[ Index ].m_SongId );
}
guListItems PlayLists;
m_Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( guMainFrame::GetMainFrame(), m_Db, &NewSongs, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == -1 )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
int PLId = m_Db->CreateStaticPlayList( PLName, NewSongs );
m_Db->UpdateStaticPlayListFile( PLId );
}
else
{
int PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
m_Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
m_Db->UpdateStaticPlayList( PLId, NewSongs );
m_Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
m_Db->AppendStaticPlayList( PLId, NewSongs );
}
m_Db->UpdateStaticPlayListFile( PLId );
}
SendPlayListUpdatedEvent();
}
PlayListAppendDlg->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewNewFilter( wxCommandEvent &event )
{
guTreeViewFilterEditor * FilterEditor = new guTreeViewFilterEditor( this, wxString( _( "New Filter" ) ) + wxT( ":" ) );
if( FilterEditor )
{
if( FilterEditor->ShowModal() == wxID_OK )
{
m_TreeViewCtrl->AppendFilterEntry( FilterEditor->GetTreeViewFilterEntry() );
}
FilterEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewEditFilter( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_TreeViewCtrl->GetFocusedItem();
if( ItemId.IsOk() && m_TreeViewCtrl->IsFilterEntry( ItemId ) )
{
guTreeViewData * ItemData = ( guTreeViewData * ) m_TreeViewCtrl->GetItemData( ItemId );
if( ItemData )
{
guTreeViewFilterEditor * FilterEditor = new guTreeViewFilterEditor( this, m_TreeViewCtrl->GetFilterEntry( ItemData->GetData() ) );
if( FilterEditor )
{
if( FilterEditor->ShowModal() == wxID_OK )
{
m_TreeViewCtrl->SetFilterEntry( ItemData->GetData(), FilterEditor->GetTreeViewFilterEntry() );
}
FilterEditor->Destroy();
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewDeleteFilter( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_TreeViewCtrl->GetFocusedItem();
if( ItemId.IsOk() && m_TreeViewCtrl->IsFilterEntry( ItemId ) )
{
guTreeViewData * ItemData = ( guTreeViewData * ) m_TreeViewCtrl->GetItemData( ItemId );
if( ItemData )
{
if( wxMessageBox( _( "Are you sure to delete the selected filter?" ),
_( "Confirm" ),
wxICON_QUESTION|wxYES_NO|wxNO_DEFAULT, this ) == wxYES )
{
m_TreeViewCtrl->DeleteFilterEntry( ItemData->GetData() );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTreeViewCopyTo( wxCommandEvent &event )
{
const wxTreeItemId &ItemId = m_TreeViewCtrl->GetFocusedItem();
if( ItemId.IsOk() && m_TreeViewCtrl->IsFilterItem( ItemId ) )
{
guTrackArray * Tracks = new guTrackArray();
m_TVTracksListBox->GetAllSongs( Tracks );
NormalizeTracks( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksActivated( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Tracks );
}
else
{
m_PlayerPanel->SetPlayList( Tracks );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksPlayClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
m_TVTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->SetPlayList( Tracks );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksQueueClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
m_TVTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->AddToPlayList( Tracks, true, event.GetId() - ID_TRACKS_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksEditLabelsClicked( wxCommandEvent &event )
{
guListItems Tracks;
m_TVTracksListBox->GetSelectedItems( &Tracks );
if( Tracks.Count() )
{
guArrayListItems LabelSets = m_Db->GetSongsLabels( m_TVTracksListBox->GetSelectedItems() );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Tracks Labels Editor" ), false, &Tracks, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the files
m_Db->UpdateSongsLabels( LabelSets );
}
LabelEditor->Destroy();
m_TVTracksListBox->ReloadItems( false );
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Tracks, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
//guUpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
//m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
m_TVTracksListBox->ReloadItems();
// Update the track in database, playlist, etc
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_TVTracksListBox->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
else
{
m_TVTracksListBox->GetAllSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
if( NewSongs.Count() )
{
guListItems PlayLists;
m_Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( guMainFrame::GetMainFrame(), m_Db, &NewSongs, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == -1 )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
int PLId = m_Db->CreateStaticPlayList( PLName, NewSongs );
m_Db->UpdateStaticPlayListFile( PLId );
}
else
{
int PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
m_Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
m_Db->UpdateStaticPlayList( PLId, NewSongs );
m_Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
m_Db->AppendStaticPlayList( PLId, NewSongs );
}
m_Db->UpdateStaticPlayListFile( PLId );
}
SendPlayListUpdatedEvent();
}
PlayListAppendDlg->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSetRating( wxCommandEvent &event )
{
int Rating = event.GetId() - ID_TRACKS_SET_RATING_0;
//guLogMessage( wxT( "OnSongSetRating( %i )" ), Rating );
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
m_MediaViewer->SetTracksRating( Tracks, Rating );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSetField( wxCommandEvent &event )
{
int ColumnId = m_TVTracksListBox->GetColumnId( m_TVTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guTreeViewPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxVariant NewData = m_TVTracksListBox->GetLastDataClicked();
//guLogMessage( wxT( "Setting Data to : %s" ), NewData.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = NewData.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = NewData.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = NewData.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = NewData.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = NewData.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = NewData.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = NewData.GetLong();
break;
}
}
m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksEditField( wxCommandEvent &event )
{
int ColumnId = m_TVTracksListBox->GetColumnId( m_TVTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxString Label = m_TVTracksListBox->GetColumnNames()[ ColumnId ];
wxVariant DefValue = m_TVTracksListBox->GetLastDataClicked();
wxArrayString Items;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxVariant Value;
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Value = ( long ) Track->m_Number;
break;
case guSONGS_COLUMN_TITLE :
Value = Track->m_SongName;
break;
case guSONGS_COLUMN_ARTIST :
Value = Track->m_ArtistName;
break;
case guSONGS_COLUMN_ALBUMARTIST :
Value = Track->m_AlbumArtist;
break;
case guSONGS_COLUMN_ALBUM :
Value = Track->m_AlbumName;
break;
case guSONGS_COLUMN_GENRE :
Value = Track->m_GenreName;
break;
case guSONGS_COLUMN_COMPOSER :
Value = Track->m_Composer;
break;
case guSONGS_COLUMN_DISK :
Value = Track->m_Disk;
break;
case guSONGS_COLUMN_YEAR :
Value = ( long ) Track->m_Year;
break;
}
if( Items.Index( Value.GetString() ) == wxNOT_FOUND )
Items.Add( Value.GetString() );
}
guEditWithOptions * FieldEditor = new guEditWithOptions( this, _( "Field Editor" ), Label, DefValue.GetString(), Items );
if( FieldEditor )
{
if( FieldEditor->ShowModal() == wxID_OK )
{
DefValue = FieldEditor->GetData();
//guLogMessage( wxT( "Setting Data to : %s" ), DefValue.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = DefValue.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = DefValue.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = DefValue.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = DefValue.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = DefValue.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = DefValue.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = DefValue.GetLong();
break;
}
}
m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
FieldEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSelectGenre( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Genres = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Genres->Index( Tracks[ index ].m_GenreId ) == wxNOT_FOUND )
{
Genres->Add( Tracks[ index ].m_GenreId );
}
}
event.SetId( ID_GENRE_SETSELECTION );
event.SetClientData( ( void * ) Genres );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSelectArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Artists = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Artists->Index( Tracks[ index ].m_ArtistId ) == wxNOT_FOUND )
{
Artists->Add( Tracks[ index ].m_ArtistId );
}
}
event.SetId( ID_ARTIST_SETSELECTION );
event.SetClientData( ( void * ) Artists );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSelectAlbumArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Ids = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Ids->Index( Tracks[ index ].m_AlbumArtistId ) == wxNOT_FOUND )
{
Ids->Add( Tracks[ index ].m_AlbumArtistId );
}
}
event.SetId( ID_ALBUMARTIST_SETSELECTION );
event.SetClientData( ( void * ) Ids );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSelectComposer( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Ids = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Ids->Index( Tracks[ index ].m_ComposerId ) == wxNOT_FOUND )
{
Ids->Add( Tracks[ index ].m_ComposerId );
}
}
event.SetId( ID_COMPOSER_SETSELECTION );
event.SetClientData( ( void * ) Ids );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksSelectAlbum( wxCommandEvent &event )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Albums = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Albums->Index( Tracks[ index ].m_AlbumId ) == wxNOT_FOUND )
{
Albums->Add( Tracks[ index ].m_AlbumId );
}
}
event.SetId( ID_ALBUM_SETSELECTION );
event.SetClientData( ( void * ) Albums );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksDeleteLibrary( wxCommandEvent &event )
{
if( m_TVTracksListBox->GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to remove the selected tracks from your library?" ),
wxT( "Remove tracks from library" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
//
m_Db->DeleteLibraryTracks( &Tracks, true );
m_TVTracksListBox->ReloadItems();
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTVTracksDeleteDrive( wxCommandEvent &event )
{
if( m_TVTracksListBox->GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to delete the selected tracks from your drive?\nThis will permanently erase the selected tracks." ),
wxT( "Remove tracks from drive" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_TVTracksListBox->GetSelectedSongs( &Tracks );
//
m_Db->DeleteLibraryTracks( &Tracks, false );
//
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( !wxRemoveFile( Tracks[ Index ].m_FileName ) )
{
guLogMessage( wxT( "Error deleting '%s'" ), Tracks[ Index ].m_FileName.c_str() );
}
}
m_TVTracksListBox->ReloadItems();
}
}
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::SendPlayListUpdatedEvent( void )
{
// wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
// wxPostEvent( guMainFrame::GetMainFrame(), evt );
m_MediaViewer->UpdatePlaylists();
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnGoToSearch( wxCommandEvent &event )
{
m_MediaViewer->GoToSearch();
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::OnTrackListColClicked( wxListEvent &event )
{
guLogMessage( wxT( "OnTrackListColClicked..." ) );
int ColId = m_TVTracksListBox->GetColumnId( event.m_col );
m_TVTracksListBox->SetTracksOrder( ColId );
// Create the Columns
wxArrayString ColumnNames = m_TVTracksListBox->GetColumnNames();
int count = ColumnNames.Count();
for( int index = 0; index < count; index++ )
{
int CurColId = m_TVTracksListBox->GetColumnId( index );
m_TVTracksListBox->SetColumnLabel( index,
ColumnNames[ CurColId ] + ( ( ColId == CurColId ) ? ( m_TVTracksListBox->GetTracksOrderDesc() ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
}
m_TVTracksListBox->ReloadItems( false );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::RefreshAll( void )
{
m_TreeViewCtrl->ReloadItems();
m_TVTracksListBox->ReloadItems( false );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
m_MediaViewer->NormalizeTracks( tracks, isdrag );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::CreateCopyToMenu( wxMenu * menu )
{
m_MediaViewer->CreateCopyToMenu( menu );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::CreateContextMenu( wxMenu * menu, const int windowid )
{
m_MediaViewer->CreateContextMenu( menu, windowid );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::UpdatedTracks( const guTrackArray * tracks )
{
m_TreeViewCtrl->ReloadItems();
m_TVTracksListBox->UpdatedTracks( tracks );
}
// -------------------------------------------------------------------------------- //
void guTreeViewPanel::UpdatedTrack( const guTrack * track )
{
m_TreeViewCtrl->ReloadItems();
m_TVTracksListBox->UpdatedTrack( track );
}
}
// -------------------------------------------------------------------------------- //
| 69,266
|
C++
|
.cpp
| 1,594
| 34.202635
| 211
| 0.546898
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,606
|
PortableMedia.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/portablemedia/PortableMedia.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PortableMedia.h"
#include "CoverEdit.h"
#include "MainFrame.h"
#include "MD5.h"
#include "SelCoverFile.h"
#include "TagInfo.h"
#include "Transcode.h"
#include "ShowImage.h"
#include "Utils.h"
#include <wx/tokenzr.h>
namespace Guayadeque {
//// -------------------------------------------------------------------------------- //
//wxString guPortableMediaAudioFormatString[] = {
// wxT( "Keep format" ),
// wxT( "mp3" ),
// wxT( "ogg" ),
// wxT( "flac" ),
// wxT( "m4a" ),
// wxT( "wma" )
//};
//
// -------------------------------------------------------------------------------- //
wxString guPortablePlaylistFormatString[] = {
wxT( "m3u" ),
wxT( "pls" ),
wxT( "xspf" ),
wxT( "asx" )
};
// -------------------------------------------------------------------------------- //
wxString guPortableCoverFormatString[] = {
wxT( "embedded" ),
wxT( "jpeg" ),
wxT( "png" ),
wxT( "bmp" ),
wxT( "gif" )
};
// -------------------------------------------------------------------------------- //
int GetPortableMediaType( const wxString &path )
{
#ifdef WITH_LIBGPOD_SUPPORT
Itdb_iTunesDB * iPodDb = itdb_parse( path.mb_str( wxConvFile ), NULL );
if( iPodDb )
{
itdb_free( iPodDb );
return guPORTABLE_MEDIA_TYPE_IPOD;
}
else
#endif
return guPORTABLE_MEDIA_TYPE_MSC;
}
// -------------------------------------------------------------------------------- //
int MimeStrToAudioFormat( const wxString &mimestr )
{
int Formats = 0;
wxArrayString AudioFormats = wxStringTokenize( mimestr, wxT( "," ) );
int Count = AudioFormats.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
AudioFormats[ Index ].Trim( true ).Trim( false );
if( AudioFormats[ Index ] == wxT( "audio/mpeg" ) )
{
Formats |= guPORTABLEMEDIA_AUDIO_FORMAT_MP3;
}
else if( AudioFormats[ Index ] == wxT( "audio/ogg" ) )
{
Formats |= guPORTABLEMEDIA_AUDIO_FORMAT_OGG;
}
else if( AudioFormats[ Index ] == wxT( "audio/flac" ) )
{
Formats |= guPORTABLEMEDIA_AUDIO_FORMAT_FLAC;
}
else if( AudioFormats[ Index ] == wxT( "audio/mp4a-latm" ) )
{
Formats |= guPORTABLEMEDIA_AUDIO_FORMAT_AAC;
}
else if( AudioFormats[ Index ] == wxT( "audio/x-ms-wma" ) )
{
Formats |= guPORTABLEMEDIA_AUDIO_FORMAT_WMA;
}
else
{
guLogMessage( wxT( "Unknown audio mime type : '%s'" ), AudioFormats[ Index ].c_str() );
}
}
}
return Formats;
}
// -------------------------------------------------------------------------------- //
wxString AudioFormatsToMimeStr( const int formats )
{
wxString MimeStr;
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_MP3 )
{
MimeStr += wxT( "audio/mpeg" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_OGG )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "audio/ogg" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_FLAC )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "audio/flac" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_AAC )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "audio/mp4a-latm" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_WMA )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "audio/x-ms-wma" );
}
return MimeStr;
}
// -------------------------------------------------------------------------------- //
int MimeStrToPlaylistFormat( const wxString &mimestr )
{
int Formats = 0;
wxArrayString PlaylistFormats = wxStringTokenize( mimestr, wxT( "," ) );
int Count = PlaylistFormats.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
PlaylistFormats[ Index ].Trim( true ).Trim( false );
if( ( PlaylistFormats[ Index ] == wxT( "audio/mpegurl" ) ) ||
( PlaylistFormats[ Index ] == wxT( "audio/x-mpegurl" ) ) )
{
Formats |= guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U;
}
else if( PlaylistFormats[ Index ] == wxT( "audio/x-scpls" ) )
{
Formats |= guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS;
}
else if( PlaylistFormats[ Index ] == wxT( "application/xspf+xml" ) )
{
Formats |= guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF;
}
else if( PlaylistFormats[ Index ] == wxT( "video/x-ms-asf" ) )
{
Formats |= guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX;
}
else
{
guLogMessage( wxT( "Unknown playlist mime type : '%s'" ), PlaylistFormats[ Index ].c_str() );
}
}
}
return Formats;
}
// -------------------------------------------------------------------------------- //
wxString PlaylistFormatsToMimeStr( const int formats )
{
wxString MimeStr;
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U )
{
MimeStr += wxT( "audio/mpegurl" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "audio/x-scpls" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "application/xspf+xml" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "video/x-ms-asf" );
}
return MimeStr;
}
// -------------------------------------------------------------------------------- //
int MimeStrToCoverFormat( const wxString &mimestr )
{
int Formats = 0;
wxArrayString CoverFormats = wxStringTokenize( mimestr, wxT( "," ) );
int Count = CoverFormats.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
CoverFormats[ Index ].Trim( true ).Trim( false );
if( CoverFormats[ Index ] == wxT( "embedded" ) )
{
Formats |= guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED;
}
else if( CoverFormats[ Index ] == wxT( "image/jpeg" ) )
{
Formats |= guPORTABLEMEDIA_COVER_FORMAT_JPEG;
}
else if( ( CoverFormats[ Index ] == wxT( "image/png" ) ) )
{
Formats |= guPORTABLEMEDIA_COVER_FORMAT_PNG;
}
else if( CoverFormats[ Index ] == wxT( "image/bmp" ) )
{
Formats |= guPORTABLEMEDIA_COVER_FORMAT_BMP;
}
else if( CoverFormats[ Index ] == wxT( "image/gif" ) )
{
Formats |= guPORTABLEMEDIA_COVER_FORMAT_GIF;
}
else
{
guLogMessage( wxT( "Unknown playlist mime type : '%s'" ), CoverFormats[ Index ].c_str() );
}
}
}
return Formats;
}
// -------------------------------------------------------------------------------- //
wxString CoverFormatsToMimeStr( const int formats )
{
wxString MimeStr;
if( formats & guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED )
{
MimeStr += wxT( "embedded" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_JPEG )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "image/jpeg" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_PNG )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "image/png" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_BMP )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "image/bmp" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_GIF )
{
if( !MimeStr.IsEmpty() )
{
MimeStr += wxT( ", " );
}
MimeStr += wxT( "image/gif" );
}
return MimeStr;
}
// -------------------------------------------------------------------------------- //
// guPortableMediaDevice
// -------------------------------------------------------------------------------- //
guPortableMediaDevice::guPortableMediaDevice( guGIO_Mount * mount )
{
m_Mount = mount;
m_Type = guPORTABLE_MEDIA_TYPE_MSC;
// On mtp devices the config file must be inside the device folder ('Internal storage', 'SD Card', etc)
m_ConfigPath = m_Mount->GetMountPath() + guPORTABLEMEDIA_CONFIG_FILE;
guLogMessage( wxT( "Using config path '%s'" ), m_ConfigPath.c_str() );
wxFileConfig * Config = new wxFileConfig( wxEmptyString, wxEmptyString, m_ConfigPath );
m_Id = mount->GetId(); //Config->Read( wxT( "audio_player_id" ), wxString::Format( wxT( "%08lX" ), wxGetLocalTime() ) );
m_Pattern = Config->Read( wxT( "audio_file_pattern" ), wxT( "{A} - {b}/{n} - {a} - {t}" ) );
m_AudioFormats = MimeStrToAudioFormat( Config->Read( wxT( "output_formats" ), wxT( "audio/mpeg" ) ) );
m_TranscodeFormat = Config->Read( wxT( "transcode_format" ), guTRANSCODE_FORMAT_KEEP );
m_TranscodeScope = Config->Read( wxT( "transcode_scope" ), guPORTABLEMEDIA_TRANSCODE_SCOPE_NOT_SUPPORTED );
m_TranscodeQuality = Config->Read( wxT( "transcode_quality" ), guTRANSCODE_QUALITY_KEEP );
m_AudioFolders = Config->Read( wxT( "audio_folders" ), wxT( "" ) );
m_PlaylistFormats = MimeStrToPlaylistFormat( Config->Read( wxT( "playlist_format" ), wxEmptyString ) );
m_PlaylistFolder = Config->Read( wxT( "playlist_path" ), wxEmptyString );
m_CoverFormats = MimeStrToCoverFormat( Config->Read( wxT( "cover_art_file_type" ), wxT( "image/jpeg" ) ) );
m_CoverName = Config->Read( wxT( "cover_art_file_name" ), wxT( "cover" ) );
m_CoverSize = Config->Read( wxT( "cover_art_size" ), 100 );
UpdateDiskFree();
Config->Write( wxT( "audio_player_id" ), m_Id );
Config->Flush();
delete Config;
}
// -------------------------------------------------------------------------------- //
guPortableMediaDevice::~guPortableMediaDevice()
{
}
// -------------------------------------------------------------------------------- //
void guPortableMediaDevice::WriteConfig( void )
{
wxFileConfig * Config = new wxFileConfig( wxEmptyString, wxEmptyString, m_ConfigPath );
Config->Write( wxT( "audio_file_pattern" ), m_Pattern );
Config->Write( wxT( "output_formats" ), AudioFormatsToMimeStr( m_AudioFormats ) );
Config->Write( wxT( "transcode_format" ), m_TranscodeFormat );
Config->Write( wxT( "transcode_scope" ), m_TranscodeScope );
Config->Write( wxT( "transcode_quality" ), m_TranscodeQuality );
Config->Write( wxT( "audio_folders" ), m_AudioFolders );
Config->Write( wxT( "playlist_format" ), PlaylistFormatsToMimeStr( m_PlaylistFormats ) );
Config->Write( wxT( "playlist_path" ), m_PlaylistFolder );
Config->Write( wxT( "cover_art_file_type" ), CoverFormatsToMimeStr( m_CoverFormats ) );
Config->Write( wxT( "cover_art_file_name" ), m_CoverName );
Config->Write( wxT( "cover_art_size" ), m_CoverSize );
Config->Flush();
delete Config;
}
// -------------------------------------------------------------------------------- //
wxString guPortableMediaDevice::AudioFormatsStr( const int formats )
{
wxString AudioFormats;
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_MP3 )
{
AudioFormats += wxT( "mp3" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_OGG )
{
if( !AudioFormats.IsEmpty() )
AudioFormats += wxT( ", " );
AudioFormats += wxT( "ogg" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_FLAC )
{
if( !AudioFormats.IsEmpty() )
AudioFormats += wxT( ", " );
AudioFormats += wxT( "flac" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_AAC )
{
if( !AudioFormats.IsEmpty() )
AudioFormats += wxT( ", " );
AudioFormats += wxT( "m4a" );
}
if( formats & guPORTABLEMEDIA_AUDIO_FORMAT_WMA )
{
if( !AudioFormats.IsEmpty() )
AudioFormats += wxT( ", " );
AudioFormats += wxT( "wma" );
}
return AudioFormats;
}
// -------------------------------------------------------------------------------- //
wxString guPortableMediaDevice::PlaylistFormatsStr( const int formats )
{
wxString Formats;
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U )
{
Formats += wxT( "m3u" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "pls" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "xspf" );
}
if( formats & guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "asx" );
}
return Formats;
}
// -------------------------------------------------------------------------------- //
wxString guPortableMediaDevice::CoverFormatsStr( const int formats )
{
wxString Formats;
if( formats & guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED )
{
Formats += _( "embedded" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_JPEG )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "jpeg" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_PNG )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "png" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_BMP )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "bmp" );
}
if( formats & guPORTABLEMEDIA_COVER_FORMAT_GIF )
{
if( !Formats.IsEmpty() )
Formats += wxT( ", " );
Formats += wxT( "gif" );
}
return Formats;
}
// -------------------------------------------------------------------------------- //
// guPortableMediaLibrary
// -------------------------------------------------------------------------------- //
guPortableMediaLibrary::guPortableMediaLibrary( const wxString &dbname, guPortableMediaDevice * portablemediadevice ) :
guDbLibrary( dbname )
{
m_PortableDevice = portablemediadevice;
}
// -------------------------------------------------------------------------------- //
guPortableMediaLibrary::~guPortableMediaLibrary()
{
}
// -------------------------------------------------------------------------------- //
void guPortableMediaLibrary::DeletePlayList( const int plid )
{
int PlayListFormats = m_PortableDevice->PlaylistFormats();
if( PlayListFormats )
{
wxString PlayListName = GetPlayListName( plid );
wxString PlayListFile = m_PortableDevice->MountPath() + m_PortableDevice->PlaylistFolder();
PlayListFile += wxT( "/" ) + PlayListName;
if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U )
{
PlayListFile += wxT( ".m3u" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS )
{
PlayListFile += wxT( ".pls" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF )
{
PlayListFile += wxT( ".xspf" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX )
{
PlayListFile += wxT( ".asx" );
}
else
{
PlayListFile += wxT( ".m3u" );
}
wxFileName FileName( PlayListFile );
if( FileName.Normalize() )
{
if( FileName.FileExists() )
{
if( !wxRemoveFile( FileName.GetFullPath() ) )
{
guLogError( wxT( "Could not delete the playlist file '%s'" ), FileName.GetFullPath().c_str() );
}
}
}
}
guDbLibrary::DeletePlayList( plid );
}
// -------------------------------------------------------------------------------- //
void guPortableMediaLibrary::UpdateStaticPlayListFile( const int plid )
{
guLogMessage( wxT( "guPortableMediaLibrary::UpdateStaticPlayListFile" ) );
int PlayListFormats = m_PortableDevice->PlaylistFormats();
if( PlayListFormats )
{
wxString PlayListName = GetPlayListName( plid );
wxString PlayListFile = m_PortableDevice->MountPath() + m_PortableDevice->PlaylistFolder();
PlayListFile += wxT( "/" ) + PlayListName;
if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U )
{
PlayListFile += wxT( ".m3u" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS )
{
PlayListFile += wxT( ".pls" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF )
{
PlayListFile += wxT( ".xspf" );
}
else if( PlayListFormats & guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX )
{
PlayListFile += wxT( ".asx" );
}
else
{
PlayListFile += wxT( ".m3u" );
}
wxFileName FileName( PlayListFile );
if( FileName.Normalize() )
{
guTrackArray Tracks;
GetPlayListSongs( plid, guPLAYLIST_TYPE_STATIC, &Tracks, NULL, NULL );
guPlaylistFile PlayListFile;
PlayListFile.SetName( FileName.GetFullPath() );
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = Tracks[ Index ];
PlayListFile.AddItem( Track.m_FileName,
Track.m_ArtistName + wxT( " - " ) + Track.m_SongName,
Track.m_Length );
}
PlayListFile.Save( FileName.GetFullPath(), true );
}
}
}
// -------------------------------------------------------------------------------- //
// guPortableMediaLibPanel
// -------------------------------------------------------------------------------- //
guPortableMediaLibPanel::guPortableMediaLibPanel( wxWindow * parent, guMediaViewerPortableDevice * mediaviewer ) :
guLibPanel( parent, mediaviewer )
{
}
// -------------------------------------------------------------------------------- //
guPortableMediaLibPanel::~guPortableMediaLibPanel()
{
}
// -------------------------------------------------------------------------------- //
wxString guPortableMediaLibPanel::GetName( void )
{
return m_PortableDevice->DeviceName();
}
// -------------------------------------------------------------------------------- //
// guPortableMediaProperties
// -------------------------------------------------------------------------------- //
guPortableMediaProperties::guPortableMediaProperties( wxWindow * parent, guPortableMediaDevice * mediadevice )
{
wxStaticText * NameLabel;
wxStaticText * MountPathLabel;
wxStaticText * UsedLabel;
wxNotebook * PMNotebook;
wxScrolledWindow * PMAudioPanel;
wxStaticText * NamePatternLabel;
wxStaticText * AudioFolderLabel;
wxStaticText * AudioFormatLabel;
wxScrolledWindow * PMPlaylistPanel;
wxStaticText * PlaylistFormatLabel;
wxStaticText * PlaylistFolderLabel;
wxScrolledWindow * PMCoversPanel;
wxStaticText * CoverFormatLabel;
wxStaticText * CoverNameLabel;
wxStaticText * CoverSizeLabel;
wxStdDialogButtonSizer * BtnSizer;
wxButton * BtnSizerOK;
wxButton * BtnSizerCancel;
m_PortableDevice = mediadevice;
m_PortableDevice->UpdateDiskFree();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPoint WindowPos;
WindowPos.x = Config->ReadNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_POSX, -1, CONFIG_PATH_POSITIONS );
WindowPos.y = Config->ReadNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_POSY, -1, CONFIG_PATH_POSITIONS );
wxSize WindowSize;
WindowSize.x = Config->ReadNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_WIDTH, 570, CONFIG_PATH_POSITIONS );
WindowSize.y = Config->ReadNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_HEIGHT, 420, CONFIG_PATH_POSITIONS );
Create( parent, wxID_ANY, _( "Portable Media Properties" ), WindowPos, WindowSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX );
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer * PMBoxSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _( " Properties " ) ), wxVERTICAL );
wxFlexGridSizer * PMFlexSizer = new wxFlexGridSizer( 2, 0, 0 );
PMFlexSizer->AddGrowableCol( 1 );
PMFlexSizer->SetFlexibleDirection( wxBOTH );
PMFlexSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
NameLabel = new wxStaticText( this, wxID_ANY, _("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
NameLabel->Wrap( -1 );
NameLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );
PMFlexSizer->Add( NameLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxTOP, 5 );
m_NameText = new wxStaticText( this, wxID_ANY, mediadevice->DeviceName(), wxDefaultPosition, wxDefaultSize, 0 );
m_NameText->Wrap( -1 );
PMFlexSizer->Add( m_NameText, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxTOP, 5 );
MountPathLabel = new wxStaticText( this, wxID_ANY, _("Path:"), wxDefaultPosition, wxDefaultSize, 0 );
MountPathLabel->Wrap( -1 );
MountPathLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );
PMFlexSizer->Add( MountPathLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 5 );
m_MountPathText = new wxStaticText( this, wxID_ANY, mediadevice->MountPath(), wxDefaultPosition, wxDefaultSize, 0 );
m_MountPathText->Wrap( -1 );
PMFlexSizer->Add( m_MountPathText, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 5 );
UsedLabel = new wxStaticText( this, wxID_ANY, _("Used:"), wxDefaultPosition, wxDefaultSize, 0 );
UsedLabel->Wrap( -1 );
PMFlexSizer->Add( UsedLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT|wxBOTTOM, 5 );
m_UsedGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxSize( -1, 17 ), wxGA_HORIZONTAL );
m_UsedGauge->SetValue( ( m_PortableDevice->DiskSize() - m_PortableDevice->DiskFree() ) * double( 100 ) / m_PortableDevice->DiskSize() );
PMFlexSizer->Add( m_UsedGauge, 1, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
//guLogMessage( wxT( "Disk %.0f free of %.0f" ), m_PortableDevice->DiskFree(), m_PortableDevice->DiskSize() );
PMFlexSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_UsedLabel = new wxStaticText( this, wxID_ANY, wxString::Format( _( "%s free of %s" ),
SizeToString( m_PortableDevice->DiskFree() ).c_str(),
SizeToString( m_PortableDevice->DiskSize() ).c_str() ), wxDefaultPosition, wxDefaultSize, 0 );
m_UsedLabel->Wrap( -1 );
PMFlexSizer->Add( m_UsedLabel, 0, wxRIGHT|wxALIGN_RIGHT, 5 );
PMBoxSizer->Add( PMFlexSizer, 0, wxEXPAND, 5 );
PMNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
PMAudioPanel = new wxScrolledWindow( PMNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
PMFlexSizer = new wxFlexGridSizer( 3, 0, 0 );
PMFlexSizer->AddGrowableCol( 1 );
PMFlexSizer->SetFlexibleDirection( wxBOTH );
PMFlexSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_IsIpod = ( m_PortableDevice->Type() == guPORTABLE_MEDIA_TYPE_IPOD );
if( !m_IsIpod )
{
NamePatternLabel = new wxStaticText( PMAudioPanel, wxID_ANY, _("Name Pattern:"), wxDefaultPosition, wxDefaultSize, 0 );
NamePatternLabel->Wrap( -1 );
PMFlexSizer->Add( NamePatternLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_NamePatternText = new wxTextCtrl( PMAudioPanel, wxID_ANY, mediadevice->Pattern(), wxDefaultPosition, wxDefaultSize, 0 );
m_NamePatternText->SetToolTip( _("{a}\t: Artist\t\t\t{aa} : Album Artist\n{b}\t: Album\t\t\t{d}\t : Disk\n{f}\t: Filename\t\t{g}\t : Genre\n{n}\t: Number\t\t\t{t}\t : Title\n{y}\t: Year") );
PMFlexSizer->Add( m_NamePatternText, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 );
PMFlexSizer->Add( 0, 0, 0, wxEXPAND, 5 );
AudioFolderLabel = new wxStaticText( PMAudioPanel, wxID_ANY, _("Audio Folders:"), wxDefaultPosition, wxDefaultSize, 0 );
AudioFolderLabel->Wrap( -1 );
PMFlexSizer->Add( AudioFolderLabel, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5 );
m_AudioFolderText = new wxTextCtrl( PMAudioPanel, wxID_ANY, mediadevice->AudioFolders(), wxDefaultPosition, wxDefaultSize, 0 );
PMFlexSizer->Add( m_AudioFolderText, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 );
m_AudioFolderBtn = new wxButton( PMAudioPanel, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 28,-1 ), 0 );
PMFlexSizer->Add( m_AudioFolderBtn, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
}
AudioFormatLabel = new wxStaticText( PMAudioPanel, wxID_ANY, _("Audio Formats:"), wxDefaultPosition, wxDefaultSize, 0 );
AudioFormatLabel->Wrap( -1 );
PMFlexSizer->Add( AudioFormatLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_AudioFormats = mediadevice->AudioFormats();
m_AudioFormatText = new wxTextCtrl( PMAudioPanel, wxID_ANY, mediadevice->AudioFormatsStr(), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
PMFlexSizer->Add( m_AudioFormatText, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 );
m_AudioFormatBtn = new wxButton( PMAudioPanel, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 28,-1 ), 0 );
PMFlexSizer->Add( m_AudioFormatBtn, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
wxStaticText * TransFormatLabel = new wxStaticText( PMAudioPanel, wxID_ANY, _("Transcode to:"), wxDefaultPosition, wxDefaultSize, 0 );
TransFormatLabel->Wrap( -1 );
PMFlexSizer->Add( TransFormatLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
wxBoxSizer* TranscodeSizer;
TranscodeSizer = new wxBoxSizer( wxHORIZONTAL );
m_TransFormatChoice = new wxChoice( PMAudioPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, guTranscodeFormatStrings( m_IsIpod ), 0 );
if( m_IsIpod )
{
guLogMessage( wxT( "Transcode Format : %i" ), mediadevice->TranscodeFormat() );
m_TransFormatChoice->SetSelection( mediadevice->TranscodeFormat() == guTRANSCODE_FORMAT_AAC );
}
else
{
m_TransFormatChoice->SetSelection( mediadevice->TranscodeFormat() );
}
TranscodeSizer->Add( m_TransFormatChoice, 1, wxEXPAND|wxTOP|wxBOTTOM, 5 );
wxString m_TransScopeChoiceChoices[] = { _( "Unsupported formats only" ), _( "always" ) };
int m_TransScopeChoiceNChoices = sizeof( m_TransScopeChoiceChoices ) / sizeof( wxString );
m_TransScopeChoice = new wxChoice( PMAudioPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_TransScopeChoiceNChoices, m_TransScopeChoiceChoices, 0 );
m_TransScopeChoice->SetSelection( mediadevice->TranscodeScope() );
if( !m_IsIpod )
m_TransScopeChoice->Enable( mediadevice->TranscodeFormat() != guTRANSCODE_FORMAT_KEEP );
TranscodeSizer->Add( m_TransScopeChoice, 0, wxTOP|wxBOTTOM|wxLEFT, 5 );
PMFlexSizer->Add( TranscodeSizer, 1, wxEXPAND, 5 );
PMFlexSizer->Add( 0, 0, 1, wxEXPAND, 5 );
wxStaticText * TransQualityLabel = new wxStaticText( PMAudioPanel, wxID_ANY, _("Quality:"), wxDefaultPosition, wxDefaultSize, 0 );
TransQualityLabel->Wrap( -1 );
PMFlexSizer->Add( TransQualityLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_TransQualityChoice = new wxChoice( PMAudioPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, guTranscodeQualityStrings(), 0 );
m_TransQualityChoice->SetSelection( mediadevice->TranscodeQuality() );
if( !m_IsIpod )
{
m_TransQualityChoice->Enable( ( m_PortableDevice->TranscodeFormat() != guTRANSCODE_FORMAT_KEEP ) );
}
PMFlexSizer->Add( m_TransQualityChoice, 0, wxEXPAND|wxTOP|wxBOTTOM|wxALIGN_CENTER_VERTICAL, 5 );
PMFlexSizer->Add( 0, 0, 1, wxEXPAND, 5 );
PMAudioPanel->SetSizer( PMFlexSizer );
PMAudioPanel->Layout();
PMFlexSizer->Fit( PMAudioPanel );
PMNotebook->AddPage( PMAudioPanel, _("Audio"), true );
PMAudioPanel->SetScrollRate( 20, 20 );
if( !m_IsIpod )
{
PMPlaylistPanel = new wxScrolledWindow( PMNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
PMFlexSizer = new wxFlexGridSizer( 3, 0, 0 );
PMFlexSizer->AddGrowableCol( 1 );
PMFlexSizer->SetFlexibleDirection( wxBOTH );
PMFlexSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
PlaylistFolderLabel = new wxStaticText( PMPlaylistPanel, wxID_ANY, _("Playlist Folders:"), wxDefaultPosition, wxDefaultSize, 0 );
PlaylistFolderLabel->Wrap( -1 );
PMFlexSizer->Add( PlaylistFolderLabel, 0, wxALIGN_CENTER_VERTICAL|wxALL|wxALIGN_RIGHT, 5 );
m_PlaylistFolderText = new wxTextCtrl( PMPlaylistPanel, wxID_ANY, mediadevice->PlaylistFolder(), wxDefaultPosition, wxDefaultSize, 0 );
PMFlexSizer->Add( m_PlaylistFolderText, 0, wxEXPAND|wxTOP|wxBOTTOM|wxALIGN_CENTER_VERTICAL, 5 );
m_PlaylistFolderBtn = new wxButton( PMPlaylistPanel, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 28,-1 ), 0 );
PMFlexSizer->Add( m_PlaylistFolderBtn, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 );
PlaylistFormatLabel = new wxStaticText( PMPlaylistPanel, wxID_ANY, _("Playlist Format:"), wxDefaultPosition, wxDefaultSize, 0 );
PlaylistFormatLabel->Wrap( -1 );
PMFlexSizer->Add( PlaylistFormatLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_PlaylistFormats = mediadevice->PlaylistFormats();
m_PlaylistFormatText = new wxTextCtrl( PMPlaylistPanel, wxID_ANY, mediadevice->PlaylistFormatsStr(), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
PMFlexSizer->Add( m_PlaylistFormatText, 0, wxEXPAND|wxTOP|wxBOTTOM|wxALIGN_CENTER_VERTICAL, 5 );
m_PlaylistFormatBtn = new wxButton( PMPlaylistPanel, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 28,-1 ), 0 );
PMFlexSizer->Add( m_PlaylistFormatBtn, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
PMPlaylistPanel->SetSizer( PMFlexSizer );
PMPlaylistPanel->Layout();
PMFlexSizer->Fit( PMPlaylistPanel );
PMNotebook->AddPage( PMPlaylistPanel, _("Playlists"), false );
PMPlaylistPanel->SetScrollRate( 20, 20 );
}
PMCoversPanel = new wxScrolledWindow( PMNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
PMFlexSizer = new wxFlexGridSizer( 3, 0, 0 );
PMFlexSizer->AddGrowableCol( 1 );
PMFlexSizer->SetFlexibleDirection( wxBOTH );
PMFlexSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
CoverFormatLabel = new wxStaticText( PMCoversPanel, wxID_ANY, _("Cover Format:"), wxDefaultPosition, wxDefaultSize, 0 );
CoverFormatLabel->Wrap( -1 );
PMFlexSizer->Add( CoverFormatLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );
m_CoverFormats = mediadevice->CoverFormats();
m_CoverFormatText = new wxTextCtrl( PMCoversPanel, wxID_ANY, mediadevice->CoverFormatsStr(), wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
PMFlexSizer->Add( m_CoverFormatText, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 );
m_CoverFormatBtn = new wxButton( PMCoversPanel, wxID_ANY, wxT("..."), wxDefaultPosition, wxSize( 28,-1 ), 0 );
PMFlexSizer->Add( m_CoverFormatBtn, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
if( !m_IsIpod )
{
CoverNameLabel = new wxStaticText( PMCoversPanel, wxID_ANY, _("Cover Name:"), wxDefaultPosition, wxDefaultSize, 0 );
CoverNameLabel->Wrap( -1 );
PMFlexSizer->Add( CoverNameLabel, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_CoverNameText = new wxTextCtrl( PMCoversPanel, wxID_ANY, mediadevice->CoverName(), wxDefaultPosition, wxDefaultSize, 0 );
PMFlexSizer->Add( m_CoverNameText, 0, wxEXPAND|wxTOP|wxBOTTOM|wxALIGN_CENTER_VERTICAL, 5 );
PMFlexSizer->Add( 0, 0, 0, wxEXPAND, 5 );
}
CoverSizeLabel = new wxStaticText( PMCoversPanel, wxID_ANY, _("Covers Size (pixels):"), wxDefaultPosition, wxDefaultSize, 0 );
CoverSizeLabel->Wrap( -1 );
PMFlexSizer->Add( CoverSizeLabel, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_CoverSizeText = new wxTextCtrl( PMCoversPanel, wxID_ANY, wxString::Format( wxT( "%u" ), mediadevice->CoverSize() ), wxDefaultPosition, wxDefaultSize, 0 );
PMFlexSizer->Add( m_CoverSizeText, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
PMCoversPanel->SetSizer( PMFlexSizer );
PMCoversPanel->Layout();
PMFlexSizer->Fit( PMCoversPanel );
PMNotebook->AddPage( PMCoversPanel, _("Covers"), false );
PMCoversPanel->SetScrollRate( 20, 20 );
PMBoxSizer->Add( PMNotebook, 1, wxEXPAND | wxLEFT|wxRIGHT|wxBOTTOM, 5 );
MainSizer->Add( PMBoxSizer, 1, wxEXPAND|wxALL, 5 );
BtnSizer = new wxStdDialogButtonSizer();
BtnSizerOK = new wxButton( this, wxID_OK );
BtnSizer->AddButton( BtnSizerOK );
BtnSizerCancel = new wxButton( this, wxID_CANCEL );
BtnSizer->AddButton( BtnSizerCancel );
BtnSizer->SetAffirmativeButton( BtnSizerOK );
BtnSizer->SetCancelButton( BtnSizerCancel );
BtnSizer->Realize();
MainSizer->Add( BtnSizer, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
BtnSizerOK->SetDefault();
if( !m_IsIpod )
m_AudioFolderBtn->Bind( wxEVT_BUTTON, &guPortableMediaProperties::OnAudioFolderBtnClick, this );
m_AudioFormatBtn->Bind( wxEVT_BUTTON, &guPortableMediaProperties::OnAudioFormatBtnClick, this );
m_TransFormatChoice->Bind( wxEVT_CHOICE, &guPortableMediaProperties::OnTransFormatChanged, this );
if( !m_IsIpod )
{
m_PlaylistFolderBtn->Bind( wxEVT_BUTTON, &guPortableMediaProperties::OnPlaylistFolderBtnClick, this );
m_PlaylistFormatBtn->Bind( wxEVT_BUTTON, &guPortableMediaProperties::OnPlaylistFormatBtnClick, this );
}
m_CoverFormatBtn->Bind( wxEVT_BUTTON, &guPortableMediaProperties::OnCoverFormatBtnClick, this );
m_NameText->SetFocus();
}
// -------------------------------------------------------------------------------- //
guPortableMediaProperties::~guPortableMediaProperties()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPoint WindowPos = GetPosition();
Config->WriteNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_POSX, WindowPos.x, CONFIG_PATH_POSITIONS );
Config->WriteNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_POSY, WindowPos.y, CONFIG_PATH_POSITIONS );
wxSize WindowSize = GetSize();
Config->WriteNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_WIDTH, WindowSize.x, CONFIG_PATH_POSITIONS );
Config->WriteNum( CONFIG_KEY_POSITIONS_PMPROPERTIES_HEIGHT, WindowSize.y, CONFIG_PATH_POSITIONS );
Config->Flush();
if( !m_IsIpod )
m_AudioFolderBtn->Unbind( wxEVT_BUTTON, &guPortableMediaProperties::OnAudioFolderBtnClick, this );
m_AudioFormatBtn->Unbind( wxEVT_BUTTON, &guPortableMediaProperties::OnAudioFormatBtnClick, this );
m_TransFormatChoice->Unbind( wxEVT_CHOICE, &guPortableMediaProperties::OnTransFormatChanged, this );
if( !m_IsIpod )
{
m_PlaylistFolderBtn->Unbind( wxEVT_BUTTON, &guPortableMediaProperties::OnPlaylistFolderBtnClick, this );
m_PlaylistFormatBtn->Unbind( wxEVT_BUTTON, &guPortableMediaProperties::OnPlaylistFormatBtnClick, this );
}
m_CoverFormatBtn->Unbind( wxEVT_BUTTON, &guPortableMediaProperties::OnCoverFormatBtnClick, this );
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::WriteConfig( void )
{
if( !m_IsIpod )
{
m_PortableDevice->SetPattern( m_NamePatternText->GetValue() );
m_PortableDevice->SetAudioFolders( m_AudioFolderText->GetValue() );
}
m_PortableDevice->SetAudioFormats( m_AudioFormats );
if( !m_IsIpod )
{
m_PortableDevice->SetTranscodeFormat( m_TransFormatChoice->GetSelection() );
}
else
{
m_PortableDevice->SetTranscodeFormat( m_TransFormatChoice->GetSelection() ? guTRANSCODE_FORMAT_AAC : guTRANSCODE_FORMAT_MP3 );
}
m_PortableDevice->SetTranscodeScope( m_TransScopeChoice->GetSelection() );
m_PortableDevice->SetTranscodeQuality( m_TransQualityChoice->GetSelection() );
if( !m_IsIpod )
{
m_PortableDevice->SetPlaylistFormats( m_PlaylistFormats );
m_PortableDevice->SetPlaylistFolder( m_PlaylistFolderText->GetValue() );
}
m_PortableDevice->SetCoverFormats( m_CoverFormats );
if( !m_IsIpod )
{
m_PortableDevice->SetCoverName( m_CoverNameText->GetValue() );
}
long CoverSize;
m_CoverSizeText->GetValue().ToLong( &CoverSize );
m_PortableDevice->SetCoverSize( CoverSize );
m_PortableDevice->WriteConfig();
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnAudioFolderBtnClick( wxCommandEvent &event )
{
wxString MountPath = m_PortableDevice->MountPath();
if( !MountPath.EndsWith( wxT( "/" ) ) )
MountPath.Append( wxT( "/" ) );
wxDirDialog * DirDialog = new wxDirDialog( this,
_( "Select audio folder" ), MountPath, wxDD_DIR_MUST_EXIST );
if( DirDialog )
{
if( DirDialog->ShowModal() == wxID_OK )
{
wxString NewFolder = DirDialog->GetPath() + wxT( "/" );
guLogMessage( wxT( "MountPath: '%s'\nFolder: '%s'" ), MountPath.c_str(), NewFolder.c_str() );
if( NewFolder.StartsWith( MountPath ) )
{
NewFolder = NewFolder.Mid( MountPath.Length() );
wxString AudioFolders = m_AudioFolderText->GetValue();
if( AudioFolders.Find( NewFolder ) == wxNOT_FOUND )
{
if( !AudioFolders.IsEmpty() )
AudioFolders.Append( wxT( ", " ) );
AudioFolders.Append( NewFolder );
m_AudioFolderText->SetValue( AudioFolders );
}
}
}
DirDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnAudioFormatBtnClick( wxCommandEvent &event )
{
wxArrayInt Selection;
wxArrayString Items;
Items.Add( guTranscodeFormatString( 1 ) );
if( !m_IsIpod )
{
Items.Add( guTranscodeFormatString( 2 ) );
Items.Add( guTranscodeFormatString( 3 ) );
}
Items.Add( guTranscodeFormatString( 4 ) );
if( !m_IsIpod )
{
Items.Add( guTranscodeFormatString( 5 ) );
}
wxArrayInt ItemFlags;
ItemFlags.Add( guPORTABLEMEDIA_AUDIO_FORMAT_MP3 );
if( !m_IsIpod )
{
ItemFlags.Add( guPORTABLEMEDIA_AUDIO_FORMAT_OGG );
ItemFlags.Add( guPORTABLEMEDIA_AUDIO_FORMAT_FLAC );
}
ItemFlags.Add( guPORTABLEMEDIA_AUDIO_FORMAT_AAC );
if( !m_IsIpod )
{
ItemFlags.Add( guPORTABLEMEDIA_AUDIO_FORMAT_WMA );
}
int Count = ItemFlags.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_AudioFormats & ItemFlags[ Index ] )
{
Selection.Add( Index );
}
}
guListCheckOptionsDialog * ListCheckOptionsDialog = new guListCheckOptionsDialog( this, _( "Audio format" ), Items, Selection );
if( ListCheckOptionsDialog )
{
if( ListCheckOptionsDialog->ShowModal() == wxID_OK )
{
ListCheckOptionsDialog->GetSelectedItems( Selection );
m_AudioFormats = 0;
int Count = Selection.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_AudioFormats |= ItemFlags[ Selection[ Index ] ];
}
m_AudioFormatText->SetValue( m_PortableDevice->AudioFormatsStr( m_AudioFormats ) );
}
ListCheckOptionsDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnPlaylistFolderBtnClick( wxCommandEvent &event )
{
wxString MountPath = m_PortableDevice->MountPath();
if( !MountPath.EndsWith( wxT( "/" ) ) )
MountPath.Append( wxT( "/" ) );
wxDirDialog * DirDialog = new wxDirDialog( this,
_( "Select audio folder" ), MountPath, wxDD_DIR_MUST_EXIST );
if( DirDialog )
{
if( DirDialog->ShowModal() == wxID_OK )
{
wxString NewFolder = DirDialog->GetPath() + wxT( "/" );
guLogMessage( wxT( "Selecting Folders: '%s'\n'%s'" ),
NewFolder.c_str(),
MountPath.c_str() );
if( NewFolder.StartsWith( MountPath ) )
{
NewFolder = NewFolder.Mid( MountPath.Length() );
if( m_PlaylistFolderText->GetValue() != NewFolder )
{
m_PlaylistFolderText->SetValue( NewFolder );
}
}
}
DirDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnPlaylistFormatBtnClick( wxCommandEvent &event )
{
wxArrayInt Selection;
wxArrayString Items;
Items.Add( guPortablePlaylistFormatString[ 0 ] );
Items.Add( guPortablePlaylistFormatString[ 1 ] );
Items.Add( guPortablePlaylistFormatString[ 2 ] );
Items.Add( guPortablePlaylistFormatString[ 3 ] );
wxArrayInt ItemFlags;
ItemFlags.Add( guPORTABLEMEDIA_PLAYLIST_FORMAT_M3U );
ItemFlags.Add( guPORTABLEMEDIA_PLAYLIST_FORMAT_PLS );
ItemFlags.Add( guPORTABLEMEDIA_PLAYLIST_FORMAT_XSPF );
ItemFlags.Add( guPORTABLEMEDIA_PLAYLIST_FORMAT_ASX );
int Count = ItemFlags.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_PlaylistFormats & ItemFlags[ Index ] )
{
Selection.Add( Index );
}
}
guListCheckOptionsDialog * ListCheckOptionsDialog = new guListCheckOptionsDialog( this, _( "Playlist format" ), Items, Selection );
if( ListCheckOptionsDialog )
{
if( ListCheckOptionsDialog->ShowModal() == wxID_OK )
{
ListCheckOptionsDialog->GetSelectedItems( Selection );
m_PlaylistFormats = 0;
int Count = Selection.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_PlaylistFormats |= ItemFlags[ Selection[ Index ] ];
}
m_PlaylistFormatText->SetValue( m_PortableDevice->PlaylistFormatsStr( m_PlaylistFormats ) );
}
ListCheckOptionsDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnCoverFormatBtnClick( wxCommandEvent &event )
{
wxArrayInt Selection;
wxArrayString Items;
Items.Add( _( "embedded" ) );
if( !m_IsIpod )
{
Items.Add( guPortableCoverFormatString[ 1 ] );
Items.Add( guPortableCoverFormatString[ 2 ] );
Items.Add( guPortableCoverFormatString[ 3 ] );
Items.Add( guPortableCoverFormatString[ 4 ] );
}
wxArrayInt ItemFlags;
ItemFlags.Add( guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED );
if( !m_IsIpod )
{
ItemFlags.Add( guPORTABLEMEDIA_COVER_FORMAT_JPEG );
ItemFlags.Add( guPORTABLEMEDIA_COVER_FORMAT_PNG );
ItemFlags.Add( guPORTABLEMEDIA_COVER_FORMAT_BMP );
ItemFlags.Add( guPORTABLEMEDIA_COVER_FORMAT_GIF );
}
int Count = ItemFlags.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_CoverFormats & ItemFlags[ Index ] )
{
Selection.Add( Index );
}
}
guListCheckOptionsDialog * ListCheckOptionsDialog = new guListCheckOptionsDialog( this, _( "Cover format" ), Items, Selection );
if( ListCheckOptionsDialog )
{
if( ListCheckOptionsDialog->ShowModal() == wxID_OK )
{
ListCheckOptionsDialog->GetSelectedItems( Selection );
m_CoverFormats = 0;
int Count = Selection.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_CoverFormats |= ItemFlags[ Selection[ Index ] ];
}
m_CoverFormatText->SetValue( m_PortableDevice->CoverFormatsStr( m_CoverFormats ) );
}
ListCheckOptionsDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPortableMediaProperties::OnTransFormatChanged( wxCommandEvent& event )
{
bool IsEnabled = ( event.GetInt() != guTRANSCODE_FORMAT_KEEP ) || m_IsIpod;
m_TransScopeChoice->Enable( IsEnabled );
m_TransQualityChoice->Enable( IsEnabled );
}
// -------------------------------------------------------------------------------- //
// guListCheckOptionsDialog
// -------------------------------------------------------------------------------- //
guListCheckOptionsDialog::guListCheckOptionsDialog( wxWindow * parent, const wxString &title,
const wxArrayString &items, const wxArrayInt &selection ) :
wxDialog( parent, wxID_ANY, title, wxDefaultPosition, wxSize( 225, 310 ), wxDEFAULT_DIALOG_STYLE )
{
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
m_CheckListBox = new wxCheckListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, items, wxLB_MULTIPLE );
int Count = selection.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_CheckListBox->Check( selection[ Index ] );
}
MainSizer->Add( m_CheckListBox, 1, wxALL|wxEXPAND, 5 );
wxStdDialogButtonSizer * ButtonSizer;
wxButton * ButtonSizerOK;
wxButton * ButtonSizerCancel;
ButtonSizer = new wxStdDialogButtonSizer();
ButtonSizerOK = new wxButton( this, wxID_OK );
ButtonSizer->AddButton( ButtonSizerOK );
ButtonSizerCancel = new wxButton( this, wxID_CANCEL );
ButtonSizer->AddButton( ButtonSizerCancel );
ButtonSizer->SetAffirmativeButton( ButtonSizerOK );
ButtonSizer->SetCancelButton( ButtonSizerCancel );
ButtonSizer->Realize();
MainSizer->Add( ButtonSizer, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
ButtonSizerOK->SetDefault();
m_CheckListBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guListCheckOptionsDialog::~guListCheckOptionsDialog()
{
}
// -------------------------------------------------------------------------------- //
int guListCheckOptionsDialog::GetSelectedItems( wxArrayInt &selection )
{
selection.Empty();
int Count = m_CheckListBox->GetCount();
for( int Index = 0; Index < Count; Index++ )
{
if( m_CheckListBox->IsChecked( Index ) )
selection.Add( Index );
}
return selection.Count();
}
//// -------------------------------------------------------------------------------- //
//// guPortableMediaViewCtrl
//// -------------------------------------------------------------------------------- //
//guPortableMediaViewCtrl::guPortableMediaViewCtrl( guMainFrame * mainframe, guGIO_Mount * mount, int basecommand )
//{
// m_MainFrame = mainframe;
// m_BaseCommand = basecommand;
// m_PortableDevice = new guPortableMediaDevice( mount );
//
// wxString DeviceDbPath = wxGetHomeDir() + wxT( "/.guayadeque/Devices/" ) + m_PortableDevice->DevicePath() + wxT( "/guayadeque.db" );
// wxFileName::Mkdir( wxPathOnly( DeviceDbPath ), 0775, wxPATH_MKDIR_FULL );
//
////////#ifdef WITH_LIBGPOD_SUPPORT
//////// Itdb_iTunesDB * iPodDb = itdb_parse( m_PortableDevice->MountPath().mb_str( wxConvFile ), NULL );
//////// if( iPodDb )
//////// {
//////// m_PortableDevice->SetType( guPORTABLE_MEDIA_TYPE_IPOD );
//////// m_Db = ( guPortableMediaLibrary * ) new guIpodLibrary( DeviceDbPath, m_PortableDevice, iPodDb );
////////
//////// guLogMessage( wxT( "Detected an Ipod with %i tracks and %i playlists" ), itdb_tracks_number( iPodDb ), itdb_playlists_number( iPodDb ) );
//////// Itdb_Device * iPodDevice = iPodDb->device;
//////// if( iPodDevice )
//////// {
//////// //guLogMessage( wxT( "Artwork support : %i" ), itdb_device_supports_artwork( iPodDevice ) );
//////// const Itdb_IpodInfo * iPodInfo = itdb_device_get_ipod_info( iPodDevice );
//////// if( iPodInfo )
//////// {
//////// guLogMessage( wxT( "Model Number : %s" ), wxString( iPodInfo->model_number, wxConvUTF8 ).c_str() );
//////// guLogMessage( wxT( "Capacity : %.0f" ), iPodInfo->capacity );
//////// guLogMessage( wxT( "Model Name : %s" ), wxString( itdb_info_get_ipod_model_name_string( iPodInfo->ipod_model ), wxConvUTF8 ).c_str() );
//////// guLogMessage( wxT( "Generation : %s" ), wxString( itdb_info_get_ipod_generation_string( iPodInfo->ipod_generation ), wxConvUTF8 ).c_str() );
//////// }
//////// }
//////// }
//////// else
////////#endif
// {
// m_Db = new guPortableMediaLibrary( DeviceDbPath, m_PortableDevice );
//// m_Db->SetLibPath( wxStringTokenize( m_PortableDevice->AudioFolders(), wxT( "," ) ) );
// }
//
// m_LibPanel = NULL;
//
// m_PlayListPanel = NULL;
// m_AlbumBrowserPanel = NULL;
// m_VisiblePanels = 0;
//}
//
//// -------------------------------------------------------------------------------- //
//guPortableMediaViewCtrl::~guPortableMediaViewCtrl()
//{
// if( m_LibPanel )
// delete m_LibPanel;
//
// if( m_PlayListPanel )
// delete m_PlayListPanel;
//
// if( m_AlbumBrowserPanel )
// delete m_AlbumBrowserPanel;
//
// if( m_PortableDevice )
// delete m_PortableDevice;
//
// if( m_Db )
// delete m_Db;
//}
//
//// -------------------------------------------------------------------------------- //
//guPortableMediaLibPanel * guPortableMediaViewCtrl::CreateLibPanel( wxWindow * parent, guPlayerPanel * playerpanel )
//{
// if( !m_LibPanel )
// {
////////#ifdef WITH_LIBGPOD_SUPPORT
//////// if( m_PortableDevice->Type() == guPORTABLE_MEDIA_TYPE_IPOD )
//////// {
//////// m_LibPanel = new guIpodMediaLibPanel( parent, ( guIpodLibrary * ) m_Db, playerpanel );
//////// }
//////// else
////////#endif
// {
//// m_LibPanel = new guPortableMediaLibPanel( parent, m_Db, playerpanel );
// }
// m_LibPanel->SetPortableMediaDevice( m_PortableDevice );
// m_LibPanel->SetBaseCommand( m_BaseCommand );
// }
// m_VisiblePanels |= guPANEL_MAIN_LIBRARY;
// return m_LibPanel;
//}
//
//// -------------------------------------------------------------------------------- //
//void guPortableMediaViewCtrl::DestroyLibPanel( void )
//{
//// if( m_LibPanel )
//// {
//// delete m_LibPanel;
//// m_LibPanel = NULL;
// m_VisiblePanels ^= guPANEL_MAIN_LIBRARY;
//// m_LibPanel->SetPanelActive( wxNOT_FOUND );
//// }
//}
//
//// -------------------------------------------------------------------------------- //
//guPortableMediaAlbumBrowser * guPortableMediaViewCtrl::CreateAlbumBrowser( wxWindow * parent, guPlayerPanel * playerpanel )
//{
////////#ifdef WITH_LIBGPOD_SUPPORT
//////// if( m_PortableDevice->Type() == guPORTABLE_MEDIA_TYPE_IPOD )
//////// {
//////// m_AlbumBrowserPanel = new guIpodAlbumBrowser( parent, ( guIpodLibrary * ) m_Db, playerpanel, ( guIpodMediaLibPanel * ) m_LibPanel );
//////// }
//////// else
////////#endif
// {
// m_AlbumBrowserPanel = new guPortableMediaAlbumBrowser( parent, m_Db, playerpanel, m_LibPanel );
// }
// //m_AlbumBrowserPanel->SetPortableMediaDevice( m_PortableDevice );
// //m_LibPanel->SetBaseCommand( m_BaseCommand );
// m_VisiblePanels |= guPANEL_MAIN_ALBUMBROWSER;
// return m_AlbumBrowserPanel;
//}
//
//// -------------------------------------------------------------------------------- //
//void guPortableMediaViewCtrl::DestroyAlbumBrowser( void )
//{
// if( m_AlbumBrowserPanel )
// {
// delete m_AlbumBrowserPanel;
// m_AlbumBrowserPanel = NULL;
// m_VisiblePanels ^= guPANEL_MAIN_ALBUMBROWSER;
// }
//}
//
//// -------------------------------------------------------------------------------- //
//guPortableMediaPlayListPanel * guPortableMediaViewCtrl::CreatePlayListPanel( wxWindow * parent, guPlayerPanel * playerpanel )
//{
////////#ifdef WITH_LIBGPOD_SUPPORT
//////// if( m_PortableDevice->Type() == guPORTABLE_MEDIA_TYPE_IPOD )
//////// {
//////// m_PlayListPanel = new guIpodPlayListPanel( parent, ( guIpodLibrary * ) m_Db, playerpanel, ( guIpodMediaLibPanel * ) m_LibPanel );
//////// }
//////// else
////////#endif
// {
// m_PlayListPanel = new guPortableMediaPlayListPanel( parent, m_Db, playerpanel, m_LibPanel );
// }
// m_VisiblePanels |= guPANEL_MAIN_PLAYLISTS;
// return m_PlayListPanel;
//}
//
//// -------------------------------------------------------------------------------- //
//void guPortableMediaViewCtrl::DestroyPlayListPanel( void )
//{
// if( m_PlayListPanel )
// {
// delete m_PlayListPanel;
// m_PlayListPanel = NULL;
// m_VisiblePanels ^= guPANEL_MAIN_PLAYLISTS;
// }
//}
// -------------------------------------------------------------------------------- //
// guMediaViewerPortableDeviceBase
// -------------------------------------------------------------------------------- //
guMediaViewerPortableDeviceBase::guMediaViewerPortableDeviceBase( wxWindow * parent, guMediaCollection &mediacollection,
const int basecmd, guMainFrame * mainframe, const int mode,
guPlayerPanel * playerpanel, guGIO_Mount * mount ) :
guMediaViewer( parent, mediacollection, basecmd, mainframe, mode, playerpanel )
{
m_PortableDevice = new guPortableMediaDevice( mount );
//m_PortableDevice->SetId( m_MediaCollection->m_UniqueId );
//m_PortableDevice->WriteConfig();
}
// -------------------------------------------------------------------------------- //
guMediaViewerPortableDeviceBase::~guMediaViewerPortableDeviceBase()
{
if( m_PortableDevice )
delete m_PortableDevice;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewerPortableDeviceBase::GetCoverName( const int albumid )
{
wxString CoverName = m_PortableDevice->CoverName();
if( CoverName.IsEmpty() )
{
CoverName = wxT( "cover" );
}
// int DevCoverFormats = m_PortableDevice->CoverFormats();
//
// if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_JPEG )
// {
// CoverName += wxT( ".jpg" );
// }
// else if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_PNG )
// {
// CoverName += wxT( ".png" );
// }
// else if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_GIF )
// {
// CoverName += wxT( ".gif" );
// }
// else if( DevCoverFormats & guPORTABLEMEDIA_COVER_FORMAT_BMP )
// {
// CoverName += wxT( ".bmp" );
// }
// else
// {
// CoverName += wxT( ".jpg" );
// }
return CoverName;
}
// -------------------------------------------------------------------------------- //
wxString guMediaViewerPortableDeviceBase::AudioPath( void )
{
wxString Path = m_PortableDevice->MountPath();
wxArrayString AudioFolders = wxStringTokenize( m_PortableDevice->AudioFolders(), wxT( "," ) );
if( AudioFolders.Count() )
{
Path += AudioFolders[ 0 ].Trim( true ).Trim( false );;
}
return Path;
}
// -------------------------------------------------------------------------------- //
wxBitmapType guMediaViewerPortableDeviceBase::GetCoverType( void )
{
int CoverFormats = m_PortableDevice->CoverFormats();
if( CoverFormats & guPORTABLEMEDIA_COVER_FORMAT_JPEG )
return wxBITMAP_TYPE_JPEG;
if( CoverFormats & guPORTABLEMEDIA_COVER_FORMAT_PNG )
return wxBITMAP_TYPE_PNG;
if( CoverFormats & guPORTABLEMEDIA_COVER_FORMAT_BMP )
return wxBITMAP_TYPE_BMP;
return wxBITMAP_TYPE_JPEG;
}
// -------------------------------------------------------------------------------- //
// guMediaViewerPortableDevice
// -------------------------------------------------------------------------------- //
guMediaViewerPortableDevice::guMediaViewerPortableDevice( wxWindow * parent, guMediaCollection &mediacollection,
const int basecmd, guMainFrame * mainframe, const int mode,
guPlayerPanel * playerpanel, guGIO_Mount * mount ) :
guMediaViewerPortableDeviceBase( parent, mediacollection, basecmd, mainframe, mode, playerpanel, mount )
{
UpdateCollectionProperties();
InitMediaViewer( mode );
}
// -------------------------------------------------------------------------------- //
guMediaViewerPortableDevice::~guMediaViewerPortableDevice()
{
}
// -------------------------------------------------------------------------------- //
void guMediaViewerPortableDevice::LoadMediaDb( void )
{
m_Db = new guPortableMediaLibrary( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId + wxT( "/guayadeque.db" ), m_PortableDevice );
m_Db->SetMediaViewer( this );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerPortableDevice::UpdateCollectionProperties( void )
{
m_MediaCollection->m_CoverWords.Empty();
m_MediaCollection->m_CoverWords.Add( m_PortableDevice->CoverName() );
m_MediaCollection->m_UpdateOnStart = true;
//m_MediaCollection->m_ScanEmbeddedCovers = false;
}
// -------------------------------------------------------------------------------- //
wxArrayString guMediaViewerPortableDevice::GetPaths( void )
{
wxArrayString Paths = wxStringTokenize( m_PortableDevice->AudioFolders(), wxT( "," ) );
int Count = Paths.Count();
for( int Index = 0; Index < Count; Index++ )
{
Paths[ Index ] = m_PortableDevice->MountPath() + Paths[ Index ];
Paths[ Index ].Replace( wxT( "//" ), wxT( "/" ) );
}
return Paths;
}
// -------------------------------------------------------------------------------- //
bool guMediaViewerPortableDevice::CreateLibraryView( void )
{
m_LibPanel = new guPortableMediaLibPanel( this, this );
m_LibPanel->SetBaseCommand( m_BaseCommand + 1 );
return true;
}
// -------------------------------------------------------------------------------- //
void guMediaViewerPortableDevice::CreateContextMenu( wxMenu * menu, const int windowid )
{
wxMenu * Menu = new wxMenu();
wxMenuItem * MenuItem;
int BaseCommand = GetBaseCommand();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY, _( "Update" ), _( "Update the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY, _( "Rescan" ), _( "Rescan the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS, _( "Search Covers" ), _( "Search the collection missing covers" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, BaseCommand + guCOLLECTION_ACTION_UNMOUNT, _( "Unmount" ), _( "Unmount the device" ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_VIEW_PROPERTIES, _( "Properties" ), _( "Show collection properties" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
menu->AppendSeparator();
menu->AppendSubMenu( Menu, m_MediaCollection->m_Name );
}
// -------------------------------------------------------------------------------- //
void guMediaViewerPortableDevice::HandleCommand( const int command )
{
if( command == guCOLLECTION_ACTION_UNMOUNT )
{
if( m_PortableDevice->CanUnmount() )
{
m_PortableDevice->Unmount();
}
}
else
{
guMediaViewer::HandleCommand( command );
}
}
// -------------------------------------------------------------------------------- //
void guMediaViewerPortableDevice::EditProperties( void )
{
guPortableMediaProperties * PortableMediaProperties = new guPortableMediaProperties( this, m_PortableDevice );
if( PortableMediaProperties )
{
if( PortableMediaProperties->ShowModal() == wxID_OK )
{
PortableMediaProperties->WriteConfig();
//
UpdateCollectionProperties();
}
PortableMediaProperties->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
| 62,565
|
C++
|
.cpp
| 1,437
| 37.857342
| 198
| 0.584226
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,607
|
DynamicPlayList.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/playlists/DynamicPlayList.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "DynamicPlayList.h"
#include "Images.h"
#include "Config.h"
#include "Utils.h"
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guFilterItemArray )
WX_DEFINE_OBJARRAY( guDynPlayListArray )
wxArrayString m_FilterFieldChoices;
wxArrayString m_FilterTextOptionChoices;
wxArrayString m_FilterLabelOptionChoices;
wxArrayString m_FilterNumberOptionChoices;
wxArrayString m_FilterYearOptionChoices;
wxArrayString m_FilterDateOptionChoices;
wxArrayString m_FilterBoolOptionChoices;
wxArrayString m_LimitChoices;
wxArrayString m_SortChoices;
wxArrayString m_FilterDateOption2Choices;
// -------------------------------------------------------------------------------- //
void inline InitArrayStrings( void )
{
if( !m_FilterFieldChoices.Count() )
{
m_FilterFieldChoices.Add( _( "Title" ) );
m_FilterFieldChoices.Add( _( "Artist" ) );
m_FilterFieldChoices.Add( _( "Album Artist" ) );
m_FilterFieldChoices.Add( _( "Album" ) );
m_FilterFieldChoices.Add( _( "Genre" ) );
m_FilterFieldChoices.Add( _( "Label" ) );
m_FilterFieldChoices.Add( _( "Composer" ) );
m_FilterFieldChoices.Add( _( "Comment" ) );
m_FilterFieldChoices.Add( _( "Path" ) );
m_FilterFieldChoices.Add( _( "Year" ) );
m_FilterFieldChoices.Add( _( "Rating" ) );
m_FilterFieldChoices.Add( _( "Length" ) );
m_FilterFieldChoices.Add( _( "Plays" ) );
m_FilterFieldChoices.Add( _( "Last Played" ) );
m_FilterFieldChoices.Add( _( "Added" ) );
m_FilterFieldChoices.Add( _( "Track Number" ) );
m_FilterFieldChoices.Add( _( "Bit Rate" ) );
m_FilterFieldChoices.Add( _( "Size" ) );
m_FilterFieldChoices.Add( _( "Disc" ) );
m_FilterFieldChoices.Add( _( "Has Cover" ) );
// }
//
// if( !m_FilterTextOptionChoices.Count() )
// {
m_FilterTextOptionChoices.Add( _("contains") );
m_FilterTextOptionChoices.Add( _("does not contain") );
m_FilterTextOptionChoices.Add( _("is") );
m_FilterTextOptionChoices.Add( _("is not") );
m_FilterTextOptionChoices.Add( _("begins with") );
m_FilterTextOptionChoices.Add( _("ends with") );
// }
//
// if( !m_FilterLabelOptionChoices.Count() )
// {
m_FilterLabelOptionChoices.Add( _("contains") );
m_FilterLabelOptionChoices.Add( _("does not contain") );
m_FilterLabelOptionChoices.Add( _("is") );
m_FilterLabelOptionChoices.Add( _("is not") );
m_FilterLabelOptionChoices.Add( _("begins with") );
m_FilterLabelOptionChoices.Add( _("ends with") );
m_FilterLabelOptionChoices.Add( _("not set") );
// }
//
// if( !m_FilterNumberOptionChoices.Count() )
// {
m_FilterNumberOptionChoices.Add( _( "is" ) );
m_FilterNumberOptionChoices.Add( _( "is not" ) );
m_FilterNumberOptionChoices.Add( _( "at least" ) );
m_FilterNumberOptionChoices.Add( _( "at most" ) );
// }
//
// if( !m_FilterYearOptionChoices.Count() )
// {
m_FilterYearOptionChoices.Add( _( "is" ) );
m_FilterYearOptionChoices.Add( _( "is not" ) );
m_FilterYearOptionChoices.Add( _( "after" ) );
m_FilterYearOptionChoices.Add( _( "before" ) );
// }
//
// if( !m_FilterDateOptionChoices.Count() )
// {
m_FilterDateOptionChoices.Add( _( "in the last" ) );
m_FilterDateOptionChoices.Add( _( "before the last" ) );
// }
//
// if( !m_FilterBoolOptionChoices.Count() )
// {
m_FilterBoolOptionChoices.Add( _( "false" ) );
m_FilterBoolOptionChoices.Add( _( "true" ) );
// }
// if( !m_LimitChoices.Count() )
// {
m_LimitChoices.Add( _( "Tracks" ) );
m_LimitChoices.Add( _( "Minutes" ) );
m_LimitChoices.Add( wxT( "MB" ) );
m_LimitChoices.Add( wxT( "GB" ) );
// }
//
// if( !m_SortChoices.Count() )
// {
m_SortChoices.Add( _( "Title" ) );
m_SortChoices.Add( _( "Artist" ) );
m_SortChoices.Add( _( "Album Artist" ) );
m_SortChoices.Add( _( "Album" ) );
m_SortChoices.Add( _( "Genre" ) );
m_SortChoices.Add( _( "Label" ) );
m_SortChoices.Add( _( "Composer" ) );
m_SortChoices.Add( _( "Year" ) );
m_SortChoices.Add( _( "Rating" ) );
m_SortChoices.Add( _( "Length" ) );
m_SortChoices.Add( _( "Plays" ) );
m_SortChoices.Add( _( "Last Played" ) );
m_SortChoices.Add( _( "Added" ) );
m_SortChoices.Add( _( "Random" ) );
// }
//
// if( !m_FilterDateOption2Choices.Count() )
// {
m_FilterDateOption2Choices.Add( _( "minutes" ) );
m_FilterDateOption2Choices.Add( _( "hours" ) );
m_FilterDateOption2Choices.Add( _( "days" ) );
m_FilterDateOption2Choices.Add( _( "weeks" ) );
m_FilterDateOption2Choices.Add( _( "months" ) );
}
}
// -------------------------------------------------------------------------------- //
// guFilterItem
// -------------------------------------------------------------------------------- //
void guFilterItem::Set( int type, int option, const wxString &text )
{
m_Type = type;
m_Option = option;
m_Text = text;
m_Number = 0;
SetFilterLabel();
}
// -------------------------------------------------------------------------------- //
void guFilterItem::Set( int type, int option, int number, int option2 )
{
m_Type = type;
m_Option = option;
m_Number = number;
m_Option2 = option2;
m_Text = wxEmptyString;
SetFilterLabel();
}
// -------------------------------------------------------------------------------- //
void guFilterItem::SetFilterLabel( void )
{
InitArrayStrings();
m_Label = m_FilterFieldChoices[ m_Type ] + wxT( " " );
switch( m_Type )
{
case guDYNAMIC_FILTER_TYPE_TITLE : // String
case guDYNAMIC_FILTER_TYPE_ARTIST :
case guDYNAMIC_FILTER_TYPE_ALBUMARTIST :
case guDYNAMIC_FILTER_TYPE_ALBUM :
case guDYNAMIC_FILTER_TYPE_GENRE :
case guDYNAMIC_FILTER_TYPE_COMPOSER :
case guDYNAMIC_FILTER_TYPE_COMMENT :
case guDYNAMIC_FILTER_TYPE_PATH :
case guDYNAMIC_FILTER_TYPE_DISK :
{
m_Label += m_FilterTextOptionChoices[ m_Option ] + wxT( " " );
m_Label += m_Text;
break;
}
case guDYNAMIC_FILTER_TYPE_LABEL :
{
m_Label += m_FilterLabelOptionChoices[ m_Option ] + wxT( " " );
m_Label += m_Text;
break;
}
case guDYNAMIC_FILTER_TYPE_YEAR : // Year
{
m_Label += m_FilterYearOptionChoices[ m_Option ];
m_Label += wxString::Format( wxT( " %u" ), m_Number );
break;
}
case guDYNAMIC_FILTER_TYPE_RATING : // Numbers
case guDYNAMIC_FILTER_TYPE_PLAYCOUNT :
case guDYNAMIC_FILTER_TYPE_TRACKNUMBER :
case guDYNAMIC_FILTER_TYPE_BITRATE :
case guDYNAMIC_FILTER_TYPE_SIZE :
{
m_Label += m_FilterNumberOptionChoices[ m_Option ];
m_Label += wxString::Format( wxT( " %u" ), m_Number );
break;
}
case guDYNAMIC_FILTER_TYPE_LENGTH : // Time
{
m_Label += m_FilterNumberOptionChoices[ m_Option ] + wxT( " " );
m_Label += LenToString( m_Number * 1000 );
break;
}
case guDYNAMIC_FILTER_TYPE_LASTPLAY :
case guDYNAMIC_FILTER_TYPE_ADDEDDATE :
{
m_Label += m_FilterDateOptionChoices[ m_Option ];
m_Label += wxString::Format( wxT( " %u " ), m_Number );
m_Label += m_FilterDateOption2Choices[ m_Option2 ];
break;
}
case guDYNAMIC_FILTER_TYPE_HASARTWORK :
{
m_Label += m_FilterBoolOptionChoices[ m_Option ];
}
}
}
// -------------------------------------------------------------------------------- //
// guDynPlayList
// -------------------------------------------------------------------------------- //
wxString guDynPlayList::ToString( void )
{
wxString RetVal = wxT( "DynPlayList0:" );
RetVal += wxString::Format( wxT( "%i:%s:%i:%i:%i:%i:%i:%i:%i:" ),
m_Id,
escape_configlist_str( m_Name ).c_str(), // Need to escape the ':'
m_Limited,
m_LimitValue,
m_LimitType,
m_Sorted,
m_SortType,
m_SortDesc,
m_AnyOption );
int Count = m_Filters.Count();
for( int Index = 0; Index < Count; Index++ )
{
guFilterItem FilterItem = m_Filters[ Index ];
RetVal += wxString::Format( wxT( "{%i;%i;%s;%i;%i;%s}:" ),
FilterItem.m_Type,
FilterItem.m_Option,
escape_configlist_str( FilterItem.m_Text ).c_str(),
FilterItem.m_Number,
FilterItem.m_Option2,
escape_configlist_str( FilterItem.m_Label ).c_str() );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void ReadFilterFromString( guFilterItem * filteritem, wxString &filterstr )
{
filterstr = filterstr.AfterFirst( wxT( '{' ) ).BeforeLast( wxT( '}' ) );
int Field = 0;
while( filterstr.Length() )
{
wxString Val = filterstr.BeforeFirst( wxT( ';' ) );
filterstr = filterstr.AfterFirst( wxT( ';' ) );
//guLogMessage( wxT( "(%i) %s" ), Field, Val.c_str() );
switch( Field )
{
case 0 :
{
filteritem->m_Type = wxAtoi( Val );
break;
}
case 1 :
{
filteritem->m_Option = wxAtoi( Val );
break;
}
case 2 :
{
filteritem->m_Text = unescape_configlist_str( Val );
break;
}
case 3 :
{
filteritem->m_Number = wxAtoi( Val );
break;
}
case 4 :
{
filteritem->m_Option2 = wxAtoi( Val );
break;
}
case 5 :
{
filteritem->m_Label = unescape_configlist_str( Val );
break;
}
}
Field++;
}
}
// -------------------------------------------------------------------------------- //
void ReadFiltersFromString( guFilterItemArray * filterarray, wxString &filterstr )
{
while( filterstr.Length() )
{
wxString Filter = filterstr.BeforeFirst( wxT( ':' ) );
filterstr = filterstr.AfterFirst( wxT( ':' ) );
if( Filter.Length() )
{
guFilterItem * FilterItem = new guFilterItem();
ReadFilterFromString( FilterItem, Filter );
filterarray->Add( FilterItem );
}
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayList::FromString( const wxString &playlist )
{
wxString Fields = playlist;
int Field = 0;
m_Filters.Empty();
while( Fields.Length() )
{
wxString Val = Fields.BeforeFirst( wxT( ':' ) );
Fields = Fields.AfterFirst( wxT( ':' ) );
switch( Field )
{
case 0 :
{
if( Val != wxT( "DynPlayList0" ) )
{
return;
}
break;
}
case 1 :
{
m_Id = wxAtoi( Val );
break;
}
case 2 :
{
m_Name = unescape_configlist_str( Val );
break;
}
case 3 :
{
m_Limited = wxAtoi( Val );
break;
}
case 4 :
{
m_LimitValue = wxAtoi( Val );
break;
}
case 5 :
{
m_LimitType = wxAtoi( Val );
break;
}
case 6 :
{
m_Sorted = wxAtoi( Val );
break;
}
case 7 :
{
m_SortType = wxAtoi( Val );
break;
}
case 8 :
{
m_SortDesc = wxAtoi( Val );
break;
}
case 9 :
{
m_AnyOption = wxAtoi( Val );
break;
}
}
Field++;
if( Field > 9 )
break;
}
ReadFiltersFromString( &m_Filters, Fields );
}
// -------------------------------------------------------------------------------- //
// guDynPlayLIstEditor
// -------------------------------------------------------------------------------- //
guDynPlayListEditor::guDynPlayListEditor( wxWindow * parent, guDynPlayList * playlist,
const bool albumfilter ) :
wxDialog( parent, wxID_ANY, albumfilter ? _( "Filter Album Browser" ) :
_( "Dynamic Playlist Editor" ), wxDefaultPosition, wxSize( 600, 400 ), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX )
{
m_PlayList = playlist;
m_Filters = &m_PlayList->m_Filters;
m_CurFilter = wxNOT_FOUND;
m_HasChanged = false;
m_AlbumFilter = albumfilter;
InitArrayStrings();
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
this->SetMinSize( wxSize( 500, 350 ) );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer * NameSizer = new wxBoxSizer( wxHORIZONTAL );
wxStaticText * NameStaticText = new wxStaticText( this, wxID_ANY, _( "Name:" ), wxDefaultPosition, wxDefaultSize, 0 );
NameStaticText->Wrap( -1 );
NameSizer->Add( NameStaticText, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
m_NameTextCtrl = new wxTextCtrl( this, wxID_ANY, playlist->m_Name, wxDefaultPosition, wxDefaultSize, 0 );
NameSizer->Add( m_NameTextCtrl, 1, wxALL|wxEXPAND, 5 );
MainSizer->Add( NameSizer, 0, wxEXPAND|wxTOP|wxRIGHT|wxLEFT, 5 );
wxStaticBoxSizer * CurFiltersSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _( " Current Filters " ) ), wxVERTICAL );
m_FiltersListBox = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
m_FiltersListBox->SetMinSize( wxSize( -1,80 ) );
int count = m_Filters->Count();
//guLogMessage( wxT( "Found %u filters" ), count );
for( int index = 0; index < count; index++ )
{
m_FiltersListBox->Append( ( * m_Filters )[ index ].GetLabel() );
//guLogMessage( wxT( "Filter %u : %s" ), index, ( * m_Filters )[ index ].GetLabel().c_str() );
}
CurFiltersSizer->Add( m_FiltersListBox, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_FilterEditSizer = new wxBoxSizer( wxHORIZONTAL );
m_FilterFieldChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterFieldChoices, 0 );
m_FilterFieldChoice->SetSelection( 0 );
m_FilterEditSizer->Add( m_FilterFieldChoice, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_FilterTextOptionChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterTextOptionChoices, 0 );
m_FilterTextOptionChoice->SetSelection( 0 );
m_FilterEditSizer->Add( m_FilterTextOptionChoice, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_FilterLabelOptionChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterLabelOptionChoices, 0 );
m_FilterLabelOptionChoice->SetSelection( 0 );
m_FilterLabelOptionChoice->Show( false );
m_FilterEditSizer->Add( m_FilterLabelOptionChoice, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_FilterText = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_FilterEditSizer->Add( m_FilterText, 1, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );
m_FilterRating = new guRating( this, GURATING_STYLE_BIG );
m_FilterRating->Show( false );
m_FilterEditSizer->Add( m_FilterRating, 1, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );
m_FilterDateOption2Choice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_FilterDateOption2Choices, 0 );
m_FilterDateOption2Choice->SetSelection( 2 );
m_FilterDateOption2Choice->Show( false );
m_FilterEditSizer->Add( m_FilterDateOption2Choice, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_LengthHours = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0, 9999 );
m_LengthHours->Show( false );
m_FilterEditSizer->Add( m_LengthHours, 1, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_LengthSeparator1 = new wxStaticText( this, wxID_ANY, wxT( ":" ) );
m_LengthSeparator1->Show( false );
m_FilterEditSizer->Add( m_LengthSeparator1, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_LengthMinutes = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0, 59 );
m_LengthMinutes->Show( false );
m_FilterEditSizer->Add( m_LengthMinutes, 1, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_LengthSeparator2 = new wxStaticText( this, wxID_ANY, wxT( ":" ) );
m_LengthSeparator2->Show( false );
m_FilterEditSizer->Add( m_LengthSeparator2, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_LengthSeconds = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0, 59 );
m_LengthSeconds->Show( false );
m_FilterEditSizer->Add( m_LengthSeconds, 1, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
m_FilterAdd = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_add ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_FilterAdd->Enable( false );
m_FilterEditSizer->Add( m_FilterAdd, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM, 5 );
m_FilterDel = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_del ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_FilterDel->Enable( false );
m_FilterEditSizer->Add( m_FilterDel, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxLEFT, 5 );
m_FilterAccept = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_accept ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_FilterAccept->Enable( false );
m_FilterEditSizer->Add( m_FilterAccept, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
CurFiltersSizer->Add( m_FilterEditSizer, 0, wxEXPAND, 5 );
MainSizer->Add( CurFiltersSizer, 1, wxEXPAND|wxALL, 5 );
if( !albumfilter )
{
wxStaticBoxSizer* ResultSizer;
ResultSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _(" Result ") ), wxVERTICAL );
wxBoxSizer* LimitSizer;
LimitSizer = new wxBoxSizer( wxHORIZONTAL );
m_LimitCheckBox = new wxCheckBox( this, wxID_ANY, _("Limit to"), wxDefaultPosition, wxDefaultSize, 0 );
m_LimitCheckBox->SetValue( m_PlayList->m_Limited );
LimitSizer->Add( m_LimitCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_LimitSpinCtrl = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0, 2147483647, 0 );
m_LimitSpinCtrl->SetValue( m_PlayList->m_LimitValue );
m_LimitSpinCtrl->Enable( m_LimitCheckBox->IsChecked() );
LimitSizer->Add( m_LimitSpinCtrl, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_LimitChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_LimitChoices, 0 );
m_LimitChoice->SetSelection( m_PlayList->m_LimitType );
m_LimitChoice->Enable( m_LimitCheckBox->IsChecked() );
LimitSizer->Add( m_LimitChoice, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
LimitSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_AddOnAnyCheckBox = new wxCheckBox( this, wxID_ANY, _("Any filter selects tracks"), wxDefaultPosition, wxDefaultSize, 0 );
m_AddOnAnyCheckBox->SetValue( m_PlayList->m_AnyOption );
m_AddOnAnyCheckBox->Enable( m_FiltersListBox->GetCount() > 1 );
LimitSizer->Add( m_AddOnAnyCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
ResultSizer->Add( LimitSizer, 1, wxEXPAND, 5 );
wxBoxSizer* SortSizer;
SortSizer = new wxBoxSizer( wxHORIZONTAL );
m_SortCheckBox = new wxCheckBox( this, wxID_ANY, _("Sort by"), wxDefaultPosition, wxDefaultSize, 0 );
m_SortCheckBox->SetValue( m_PlayList->m_Sorted );
SortSizer->Add( m_SortCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 );
m_SortChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_SortChoices, 0 );
m_SortChoice->SetSelection( m_PlayList->m_SortType );
m_SortChoice->Enable( m_SortCheckBox->IsChecked() );
SortSizer->Add( m_SortChoice, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 );
m_DescCheckBox = new wxCheckBox( this, wxID_ANY, _("Descending"), wxDefaultPosition, wxDefaultSize, 0 );
m_DescCheckBox->SetValue( m_PlayList->m_SortDesc );
m_DescCheckBox->Enable( m_SortCheckBox->IsChecked() );
SortSizer->Add( m_DescCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 );
ResultSizer->Add( SortSizer, 1, wxEXPAND, 5 );
MainSizer->Add( ResultSizer, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
}
else
{
wxBoxSizer* LimitSizer;
LimitSizer = new wxBoxSizer( wxHORIZONTAL );
LimitSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_AddOnAnyCheckBox = new wxCheckBox( this, wxID_ANY, _("Add tracks on any criteria"), wxDefaultPosition, wxDefaultSize, 0 );
m_AddOnAnyCheckBox->SetValue( m_PlayList->m_AnyOption );
m_AddOnAnyCheckBox->Enable( m_FiltersListBox->GetCount() > 1 );
LimitSizer->Add( m_AddOnAnyCheckBox, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
MainSizer->Add( LimitSizer, 0, wxEXPAND, 5 );
}
wxStdDialogButtonSizer * ButtonsSizer;
wxButton * BtnCancel;
ButtonsSizer = new wxStdDialogButtonSizer();
m_BtnOk = new wxButton( this, wxID_OK );
m_BtnOk->Enable( m_Filters->Count() && !m_NameTextCtrl->IsEmpty() );
ButtonsSizer->AddButton( m_BtnOk );
BtnCancel = new wxButton( this, wxID_CANCEL );
ButtonsSizer->AddButton( BtnCancel );
ButtonsSizer->SetAffirmativeButton( m_BtnOk );
ButtonsSizer->SetCancelButton( BtnCancel );
ButtonsSizer->Realize();
MainSizer->Add( ButtonsSizer, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
this->SetSizer( MainSizer );
this->Layout();
m_BtnOk->SetDefault();
// Bind Events
m_FiltersListBox->Bind( wxEVT_LISTBOX, &guDynPlayListEditor::OnFiltersSelected, this );
m_FilterFieldChoice->Bind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterFieldSelected, this );
m_FilterTextOptionChoice->Bind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterOptionSelected, this );
m_FilterLabelOptionChoice->Bind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterOptionSelected, this );
m_FilterText->Bind( wxEVT_TEXT, &guDynPlayListEditor::OnFilterTextChanged, this );
m_FilterRating->Bind( guEVT_RATING_CHANGED, &guDynPlayListEditor::OnRatingChanged, this );
m_FilterDateOption2Choice->Bind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterDateOption2Selected, this );
m_FilterAdd->Bind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterAddClicked, this );
m_FilterDel->Bind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterDelClicked, this );
m_FilterAccept->Bind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterUpdateClicked, this );
if( !m_AlbumFilter )
{
m_LimitCheckBox->Bind( wxEVT_CHECKBOX, &guDynPlayListEditor::OnLimitChecked, this );
m_SortCheckBox->Bind( wxEVT_CHECKBOX, &guDynPlayListEditor::OnSortChecked, this );
}
m_NameTextCtrl->Bind( wxEVT_TEXT, &guDynPlayListEditor::OnNameChanged, this );
m_LengthHours->Bind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnHoursChanged, this );
m_LengthMinutes->Bind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnMinutesChanged, this );
m_LengthSeconds->Bind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnSecondsChanged, this );
m_FiltersListBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guDynPlayListEditor::~guDynPlayListEditor()
{
m_FiltersListBox->Unbind( wxEVT_LISTBOX, &guDynPlayListEditor::OnFiltersSelected, this );
m_FilterFieldChoice->Unbind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterFieldSelected, this );
m_FilterTextOptionChoice->Unbind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterOptionSelected, this );
m_FilterLabelOptionChoice->Unbind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterOptionSelected, this );
m_FilterText->Unbind( wxEVT_TEXT, &guDynPlayListEditor::OnFilterTextChanged, this );
m_FilterRating->Unbind( guEVT_RATING_CHANGED, &guDynPlayListEditor::OnRatingChanged, this );
m_FilterDateOption2Choice->Unbind( wxEVT_CHOICE, &guDynPlayListEditor::OnFilterDateOption2Selected, this );
m_FilterAdd->Unbind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterAddClicked, this );
m_FilterDel->Unbind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterDelClicked, this );
m_FilterAccept->Unbind( wxEVT_BUTTON, &guDynPlayListEditor::OnFilterUpdateClicked, this );
if( !m_AlbumFilter )
{
m_LimitCheckBox->Unbind( wxEVT_CHECKBOX, &guDynPlayListEditor::OnLimitChecked, this );
m_SortCheckBox->Unbind( wxEVT_CHECKBOX, &guDynPlayListEditor::OnSortChecked, this );
}
m_NameTextCtrl->Unbind( wxEVT_TEXT, &guDynPlayListEditor::OnNameChanged, this );
m_LengthHours->Unbind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnHoursChanged, this );
m_LengthMinutes->Unbind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnMinutesChanged, this );
m_LengthSeconds->Unbind( wxEVT_SPINCTRL, &guDynPlayListEditor::OnSecondsChanged, this );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::FillPlayListEditData( void )
{
m_PlayList->m_Name = m_NameTextCtrl->GetValue();
if( !m_AlbumFilter )
{
m_PlayList->m_Limited = m_LimitCheckBox->IsChecked();
m_PlayList->m_LimitValue = m_LimitSpinCtrl->GetValue();
m_PlayList->m_LimitType = m_LimitChoice->GetSelection();
m_PlayList->m_Sorted = m_SortCheckBox->IsChecked();
m_PlayList->m_SortType = m_SortChoice->GetSelection();
m_PlayList->m_SortDesc = m_DescCheckBox->IsChecked();
}
else
{
m_PlayList->m_Limited = false;
m_PlayList->m_LimitValue = 0;
m_PlayList->m_LimitType = 0;
m_PlayList->m_Sorted = false;
m_PlayList->m_SortType = 0;
m_PlayList->m_SortDesc = false;
}
m_PlayList->m_AnyOption = m_AddOnAnyCheckBox->IsChecked();
}
// -------------------------------------------------------------------------------- //
guFilterItem guDynPlayListEditor::GetFilterItem( void )
{
guFilterItem FilterItem;
int FilterType = m_FilterFieldChoice->GetSelection();
if( FilterType == guDYNAMIC_FILTER_TYPE_LABEL )
{
FilterItem.Set( FilterType,
m_FilterLabelOptionChoice->GetSelection(),
FilterItem.m_Text = m_FilterText->GetValue() );
}
else if( ( FilterType < guDYNAMIC_FILTER_TYPE_YEAR ) ||
( FilterType == guDYNAMIC_FILTER_TYPE_DISK ) )
{
FilterItem.Set( FilterType,
m_FilterTextOptionChoice->GetSelection(),
FilterItem.m_Text = m_FilterText->GetValue() );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_RATING )
{
FilterItem.Set( FilterType,
m_FilterTextOptionChoice->GetSelection(),
m_FilterRating->GetRating(),
0 );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_LENGTH )
{
unsigned long hour = m_LengthHours->GetValue();
unsigned long min = m_LengthMinutes->GetValue();
unsigned long sec = m_LengthSeconds->GetValue();
FilterItem.Set( FilterType,
m_FilterTextOptionChoice->GetSelection(),
( hour * 3600 ) + ( min * 60 ) + sec,
0 );
}
else if( ( FilterType == guDYNAMIC_FILTER_TYPE_LASTPLAY ) ||
( FilterType == guDYNAMIC_FILTER_TYPE_ADDEDDATE ) )
{
unsigned long value = 0;
m_FilterText->GetValue().ToULong( &value );
FilterItem.Set( FilterType,
m_FilterTextOptionChoice->GetSelection(),
value,
m_FilterDateOption2Choice->GetSelection() );
}
else // FilterType == guDYNAMIC_FILTER_TYPE_YEAR
{
unsigned long value = 0;
m_FilterText->GetValue().ToULong( &value );
FilterItem.Set( FilterType,
m_FilterTextOptionChoice->GetSelection(),
value,
0 );
}
return FilterItem;
}
// -------------------------------------------------------------------------------- //
bool guDynPlayListEditor::FilterHasChanged( void )
{
return m_HasChanged;
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::UpdateEditor( int FilterType )
{
switch( FilterType )
{
case guDYNAMIC_FILTER_TYPE_RATING :
case guDYNAMIC_FILTER_TYPE_LENGTH :
case guDYNAMIC_FILTER_TYPE_HASARTWORK :
m_FilterAdd->Enable( true );
break;
default :
m_FilterAdd->Enable( false );
break;
}
m_FilterText->Enable( FilterType != guDYNAMIC_FILTER_TYPE_HASARTWORK );
if( FilterType == guDYNAMIC_FILTER_TYPE_RATING )
{
m_FilterText->Show( false );
m_FilterTextOptionChoice->Show( true );
m_FilterLabelOptionChoice->Show( false );
m_FilterRating->Show( true );
m_FilterRating->SetRating( 0 );
m_FilterDateOption2Choice->Show( false );
m_LengthHours->Show( false );
m_LengthSeparator1->Show( false );
m_LengthMinutes->Show( false );
m_LengthSeparator2->Show( false );
m_LengthSeconds->Show( false );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_LENGTH )
{
m_FilterText->Show( false );
m_FilterTextOptionChoice->Show( true );
m_FilterLabelOptionChoice->Show( false );
m_FilterRating->Show( false );
m_FilterDateOption2Choice->Show( false );
m_LengthHours->Show( true );
m_LengthSeparator1->Show( true );
m_LengthMinutes->Show( true );
m_LengthSeparator2->Show( true );
m_LengthSeconds->Show( true );
}
else if( ( FilterType == guDYNAMIC_FILTER_TYPE_LASTPLAY ) ||
( FilterType == guDYNAMIC_FILTER_TYPE_ADDEDDATE ) )
{
m_FilterText->Show( true );
m_FilterTextOptionChoice->Show( true );
m_FilterLabelOptionChoice->Show( false );
m_FilterRating->Show( false );
m_FilterDateOption2Choice->Show( true );
m_LengthHours->Show( false );
m_LengthSeparator1->Show( false );
m_LengthMinutes->Show( false );
m_LengthSeparator2->Show( false );
m_LengthSeconds->Show( false );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_LABEL )
{
m_FilterText->Show( true );
m_FilterTextOptionChoice->Show( false );
m_FilterLabelOptionChoice->Show( true );
m_FilterRating->Show( false );
m_FilterDateOption2Choice->Show( false );
m_LengthHours->Show( false );
m_LengthSeparator1->Show( false );
m_LengthMinutes->Show( false );
m_LengthSeparator2->Show( false );
m_LengthSeconds->Show( false );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_HASARTWORK )
{
m_FilterText->Show( true );
m_FilterTextOptionChoice->Show( true );
m_FilterLabelOptionChoice->Show( false );
m_FilterRating->Show( false );
m_FilterDateOption2Choice->Show( false );
m_LengthHours->Show( false );
m_LengthSeparator1->Show( false );
m_LengthMinutes->Show( false );
m_LengthSeparator2->Show( false );
m_LengthSeconds->Show( false );
}
else
{
m_FilterText->Show( true );
m_FilterTextOptionChoice->Show( true );
m_FilterLabelOptionChoice->Show( false );
m_FilterRating->Show( false );
m_FilterDateOption2Choice->Show( false );
m_LengthHours->Show( false );
m_LengthSeparator1->Show( false );
m_LengthMinutes->Show( false );
m_LengthSeparator2->Show( false );
m_LengthSeconds->Show( false );
}
m_FilterTextOptionChoice->Clear();
if( ( FilterType < guDYNAMIC_FILTER_TYPE_YEAR ) ||
( FilterType == guDYNAMIC_FILTER_TYPE_DISK ) )
{
m_FilterTextOptionChoice->Append( m_FilterTextOptionChoices );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_YEAR )
{
m_FilterTextOptionChoice->Append( m_FilterYearOptionChoices );
}
else if( ( FilterType == guDYNAMIC_FILTER_TYPE_LASTPLAY ) ||
( FilterType == guDYNAMIC_FILTER_TYPE_ADDEDDATE ) )
{
m_FilterTextOptionChoice->Append( m_FilterDateOptionChoices );
}
else if( FilterType == guDYNAMIC_FILTER_TYPE_HASARTWORK )
{
m_FilterTextOptionChoice->Append( m_FilterBoolOptionChoices );
}
else //if( FilterType < guDYNAMIC_FILTER_TYPE_LASTPLAY )
{
m_FilterTextOptionChoice->Append( m_FilterNumberOptionChoices );
}
m_FilterTextOptionChoice->SetSelection( 0 );
m_FilterLabelOptionChoice->SetSelection( 0 );
m_FilterEditSizer->Layout();
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFiltersSelected( wxCommandEvent &event )
{
m_CurFilter = event.GetInt();
if( m_CurFilter != wxNOT_FOUND )
{
guFilterItem * FilterItem = &( * m_Filters )[ m_CurFilter ];
UpdateEditor( FilterItem->m_Type );
m_FilterFieldChoice->SetSelection( FilterItem->m_Type );
//guLogMessage( wxT( "Type : %u Option: %u" ), FilterItem->m_Type, FilterItem->m_Option );
if( FilterItem->m_Type == guDYNAMIC_FILTER_TYPE_LABEL )
m_FilterLabelOptionChoice->SetSelection( FilterItem->m_Option );
else
m_FilterTextOptionChoice->SetSelection( FilterItem->m_Option );
if( ( FilterItem->m_Type < guDYNAMIC_FILTER_TYPE_YEAR ) ||
( FilterItem->m_Type == guDYNAMIC_FILTER_TYPE_DISK ) )
{
m_FilterText->SetValue( FilterItem->m_Text );
}
else if( FilterItem->m_Type == guDYNAMIC_FILTER_TYPE_RATING )
{
m_FilterRating->SetRating( FilterItem->m_Number );
}
else if( FilterItem->m_Type == guDYNAMIC_FILTER_TYPE_LENGTH )
{
unsigned long value = FilterItem->m_Number;
m_LengthHours->SetValue( int( value / 3600 ) );
value = value % 3600;
m_LengthMinutes->SetValue( int( value / 60 ) );
value = value % 60;
m_LengthSeconds->SetValue( value );
}
else
{
m_FilterText->SetValue( wxString::Format( wxT( "%u" ), FilterItem->m_Number ) );
}
m_FilterDateOption2Choice->SetSelection( FilterItem->m_Option2 );
//m_Filter
m_FilterDel->Enable( true );
m_FilterAccept->Enable( false );
m_HasChanged = false;
}
else
{
m_FilterDel->Enable( false );
m_FilterAccept->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterFieldSelected( wxCommandEvent &event )
{
int FilterType = event.GetInt();
m_FilterText->SetValue( wxEmptyString );
m_LengthHours->SetValue( 0 );
m_LengthMinutes->SetValue( 0 );
m_LengthSeconds->SetValue( 0 );
m_FilterRating->SetRating( 0 );
UpdateEditor( FilterType );
if( m_CurFilter != wxNOT_FOUND )
{
m_HasChanged = true;
m_FilterAccept->Enable( true );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterOptionSelected( wxCommandEvent &event )
{
bool IsNotSetLabel = ( m_FilterFieldChoice->GetSelection() == guDYNAMIC_FILTER_TYPE_LENGTH ) ||
( m_FilterFieldChoice->GetSelection() == guDYNAMIC_FILTER_TYPE_HASARTWORK ) ||
( ( m_FilterFieldChoice->GetSelection() == guDYNAMIC_FILTER_TYPE_LABEL ) &&
( m_FilterLabelOptionChoice->GetSelection() == guDYNAMIC_FILTER_OPTION_LABELS_NOTSET ) );
//guLogMessage( wxT( "IsNotSetLabel: %i" ), IsNotSetLabel );
m_FilterText->Enable( !IsNotSetLabel );
if( IsNotSetLabel )
m_FilterText->SetValue( wxEmptyString );
m_FilterAdd->Enable( IsNotSetLabel || !m_FilterText->IsEmpty() );
if( m_CurFilter != wxNOT_FOUND )
{
m_HasChanged = true;
m_FilterAccept->Enable( true );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterDateOption2Selected( wxCommandEvent &event )
{
if( m_CurFilter != wxNOT_FOUND )
{
m_HasChanged = true;
m_FilterAccept->Enable( true );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterTextChanged( wxCommandEvent& event )
{
wxString FilterText = event.GetString();
int FilterType = m_FilterFieldChoice->GetSelection();
if( ( FilterType > guDYNAMIC_FILTER_TYPE_PATH ) &&
( FilterType != guDYNAMIC_FILTER_TYPE_DISK ) )
{
unsigned long value = 0;
if( !FilterText.IsEmpty() && !FilterText.ToULong( &value ) )
{
m_FilterText->ChangeValue( wxEmptyString );
//m_FilterText->SetValue( wxEmptyString );
}
}
bool Enable = !FilterText.IsEmpty() ||
( ( m_FilterFieldChoice->GetSelection() == guDYNAMIC_FILTER_TYPE_LABEL ) &&
( m_FilterLabelOptionChoice->GetSelection() == guDYNAMIC_FILTER_OPTION_LABELS_NOTSET ) );
m_FilterAdd->Enable( Enable );
if( m_CurFilter != wxNOT_FOUND )
{
m_HasChanged = true;
m_FilterAccept->Enable( Enable );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnRatingChanged( guRatingEvent &event )
{
m_FilterAdd->Enable( m_FilterRating->GetRating() >= 0 );
if( m_CurFilter != wxNOT_FOUND )
{
m_HasChanged = true;
m_FilterAccept->Enable( true );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterAddClicked( wxCommandEvent& event )
{
guFilterItem FilterItem = GetFilterItem();
m_Filters->Add( FilterItem );
m_FiltersListBox->Append( FilterItem.GetLabel() );
m_FiltersListBox->Refresh();
m_BtnOk->Enable( m_Filters->Count() && !m_NameTextCtrl->IsEmpty() );
m_AddOnAnyCheckBox->Enable( m_FiltersListBox->GetCount() > 1 );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterDelClicked( wxCommandEvent& event )
{
if( m_CurFilter != wxNOT_FOUND )
{
m_Filters->RemoveAt( m_CurFilter );
m_FiltersListBox->Delete( m_CurFilter );
m_CurFilter = wxNOT_FOUND;
m_BtnOk->Enable( m_Filters->Count() );
m_AddOnAnyCheckBox->Enable( m_FiltersListBox->GetCount() > 1 );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnFilterUpdateClicked( wxCommandEvent& event )
{
if( m_CurFilter != wxNOT_FOUND )
{
guFilterItem FilterItem = GetFilterItem();
( * m_Filters )[ m_CurFilter ] = FilterItem;
m_FiltersListBox->SetString( m_CurFilter, FilterItem.GetLabel() );
m_FilterAccept->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnLimitChecked( wxCommandEvent &event )
{
m_LimitChoice->Enable( m_LimitCheckBox->IsChecked() );
m_LimitSpinCtrl->Enable( m_LimitCheckBox->IsChecked() );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnSortChecked( wxCommandEvent &event )
{
m_DescCheckBox->Enable( m_SortCheckBox->IsChecked() );
m_SortChoice->Enable( m_SortCheckBox->IsChecked() );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnNameChanged( wxCommandEvent &event )
{
m_BtnOk->Enable( m_Filters->Count() && !event.GetString().IsEmpty() );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnHoursChanged( wxSpinEvent &event )
{
m_FilterAccept->Enable( m_CurFilter != wxNOT_FOUND );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnMinutesChanged( wxSpinEvent &event )
{
m_FilterAccept->Enable( m_CurFilter != wxNOT_FOUND );
}
// -------------------------------------------------------------------------------- //
void guDynPlayListEditor::OnSecondsChanged( wxSpinEvent &event )
{
m_FilterAccept->Enable( m_CurFilter != wxNOT_FOUND );
}
}
// -------------------------------------------------------------------------------- //
| 42,609
|
C++
|
.cpp
| 986
| 36.08215
| 143
| 0.589339
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,608
|
PLSoListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/playlists/PLSoListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PLSoListBox.h"
#include "Accelerators.h"
#include "Config.h" // Configuration
#include "EventCommandIds.h"
#include "DynamicPlayList.h"
#include "Images.h"
#include "MainApp.h"
#include "OnlineLinks.h"
#include "RatingCtrl.h"
#include "TagInfo.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guPLSoListBox::guPLSoListBox( wxWindow * parent, guMediaViewer * mediaviewer, wxString confname, int style ) :
guSoListBox( parent, mediaviewer, confname, style | guLISTVIEW_ALLOWDRAG | guLISTVIEW_ALLOWDROP | guLISTVIEW_DRAGSELFITEMS | guLISTVIEW_COLUMN_SORTING )
{
m_TracksOrder = wxNOT_FOUND;
m_DisableSorting = false;
Bind( wxEVT_MENU, &guPLSoListBox::OnRandomizeTracks, this, ID_TRACKS_RANDOMIZE );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guPLSoListBox::~guPLSoListBox()
{
Unbind( wxEVT_MENU, &guPLSoListBox::OnRandomizeTracks, this, ID_TRACKS_RANDOMIZE );
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_RANDOMPLAY );
RealAccelCmds.Add( ID_TRACKS_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_TRACKS_EDITLABELS );
RealAccelCmds.Add( ID_TRACKS_EDITTRACKS );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_TRACKS_RANDOMIZE );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::GetItemsList( void )
{
m_PLSetIds.Empty();
if( m_PLIds.Count() )
{
m_Db->GetPlayListSongs( m_PLIds, m_PLTypes, &m_Items, &m_PLSetIds, &m_TracksLength, &m_TracksSize, m_TracksOrder, m_TracksOrderDesc );
//m_Db->GetPlayListSetIds( m_PLIds, &m_PLSetIds, m_TracksOrder, m_TracksOrderDesc );
}
else
{
m_Items.Empty();
}
SetItemCount( m_Items.Count() );
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::SetPlayList( int plid, int pltype )
{
m_PLIds.Empty();
m_PLTypes.Empty();
if( plid != wxNOT_FOUND )
{
m_PLIds.Add( plid );
m_PLTypes.Add( pltype );
if( pltype == guPLAYLIST_TYPE_DYNAMIC )
{
guDynPlayList DynPlayList;
m_Db->GetDynamicPlayList( plid, &DynPlayList );
m_DisableSorting = false;
if( DynPlayList.m_Sorted )
{
SetTracksOrder( wxNOT_FOUND );
m_DisableSorting = true;
return;
}
}
}
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::SetPlayList( const wxArrayInt &ids, const wxArrayInt &types )
{
m_PLIds = ids;
m_PLTypes = types;
if( m_DisableSorting )
{
m_DisableSorting = false;
}
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
if( SelCount )
{
guSoListBox::CreateContextMenu( Menu );
int InsertPosition = 12;
if( !m_DisableSorting && ( m_TracksOrder == wxNOT_FOUND ) )
{
MenuItem = new wxMenuItem( Menu, ID_TRACKS_RANDOMIZE,
wxString( _( "Randomize Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_RANDOMPLAY ),
_( "Randomize the songs in the playlist" ) );
Menu->Insert( 9, MenuItem );
InsertPosition = 13;
}
if( ( m_PLTypes.Count() == 1 ) && ( m_PLTypes[ 0 ] == guPLAYLIST_TYPE_STATIC ) )
{
MenuItem = new wxMenuItem( Menu, ID_TRACKS_DELETE, _( "Remove from Playlist" ), _( "Delete the current selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_del ) );
Menu->Insert( InsertPosition, MenuItem );
}
}
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::OnKeyDown( wxKeyEvent &event )
{
if( event.GetKeyCode() == WXK_DELETE )
{
wxCommandEvent evt( wxEVT_MENU, ID_TRACKS_DELETE );
GetParent()->GetEventHandler()->AddPendingEvent( evt );
return;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::OnDropFile( const wxString &filename )
{
if( ( m_PLIds.Count() == 1 ) && m_PLTypes[ 0 ] == guPLAYLIST_TYPE_STATIC )
{
//guLogMessage( wxT( "Adding file '%s'" ), filename.c_str() );
if( guIsValidAudioFile( filename ) )
{
if( wxFileExists( filename ) )
{
guTrack Track;
if( m_Db->FindTrackFile( filename, &Track ) )
{
m_DropIds.Add( Track.m_SongId );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::OnDropEnd( void )
{
wxArrayInt ItemIds;
if( ( m_PLIds.Count() == 1 ) && ( m_PLTypes[ 0 ] == guPLAYLIST_TYPE_STATIC ) )
{
if( m_DropIds.Count() )
{
int count = m_Items.Count();
for( int index = 0; index < count; index++ )
{
ItemIds.Add( m_Items[ index ].m_SongId );
}
//int InsertPos = m_DragOverItem + m_DragOverAfter;
int InsertPos = m_DragOverItem + m_DragOverAfter;
if( m_DragOverItem == wxNOT_FOUND )
InsertPos = m_Items.Count();
//guLogMessage( wxT( "Pos: %i + %i %i of %i " ), m_DragOverItem, m_DragOverAfter, InsertPos, m_Items.Count() );
count = m_DropIds.Count();
for( int index = 0; index < count; index++ )
{
ItemIds.Insert( m_DropIds[ index ], InsertPos + index );
}
// Save it to the database
m_Db->UpdateStaticPlayList( m_PLIds[ 0 ], ItemIds );
m_Db->UpdateStaticPlayListFile( m_PLIds[ 0 ] );
m_DropIds.Clear();
}
ReloadItems();
}
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::MoveSelection( void )
{
if( ( m_TracksOrder != wxNOT_FOUND ) ||
( m_PLIds.Count() != 1 ) ||
( m_PLTypes[ 0 ] != guPLAYLIST_TYPE_STATIC ) )
return;
wxArrayInt MoveIds;
wxArrayInt MoveIndex;
wxArrayInt ItemIds;
// Copy the elements we are going to move
unsigned long cookie;
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
MoveIndex.Add( item );
MoveIds.Add( m_Items[ item ].m_SongId );
item = GetNextSelected( cookie );
}
// Get the position where to move it
int InsertPos;
if( m_DragOverItem != wxNOT_FOUND )
InsertPos = m_DragOverItem + m_DragOverAfter;
else
InsertPos = m_Items.Count();
// Remove the elements from the original position
int count = MoveIndex.Count();
for( int index = count - 1; index >= 0; index-- )
{
m_Items.RemoveAt( MoveIndex[ index ] );
if( MoveIndex[ index ] < InsertPos )
InsertPos--;
}
count = m_Items.Count();
for( int index = 0; index < count; index++ )
{
ItemIds.Add( m_Items[ index ].m_SongId );
}
count = MoveIds.Count();
for( int index = 0; index < count; index++ )
{
ItemIds.Insert( MoveIds[ index ], InsertPos + index );
}
// Save it to the database
m_Db->UpdateStaticPlayList( m_PLIds[ 0 ], ItemIds );
m_Db->UpdateStaticPlayListFile( m_PLIds[ 0 ] );
ReloadItems();
}
// -------------------------------------------------------------------------------- //
int guPLSoListBox::GetPlayListSetIds( wxArrayInt * setids ) const
{
unsigned long cookie;
if( m_PLSetIds.Count() )
{
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
setids->Add( m_PLSetIds[ item ] );
item = GetNextSelected( cookie );
}
}
return setids->Count();
}
// -------------------------------------------------------------------------------- //
int guPLSoListBox::GetSelectedSongs( guTrackArray * tracks, const bool isdrag ) const
{
unsigned long cookie;
guPLSoListBox * self = wxConstCast( this, guPLSoListBox );
self->m_ItemsMutex.Lock();
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
tracks->Add( new guTrack( m_Items[ item ] ) );
item = GetNextSelected( cookie );
}
self->m_ItemsMutex.Unlock();
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::GetAllSongs( guTrackArray * tracks )
{
m_ItemsMutex.Lock();
int count = m_Items.Count();
for( int index = 0; index < count; index++ )
{
tracks->Add( new guTrack( m_Items[ index ] ) );
}
m_ItemsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
wxString guPLSoListBox::GetItemName( const int row ) const
{
return m_Items[ row ].m_SongName;
}
// -------------------------------------------------------------------------------- //
int guPLSoListBox::GetItemId( const int row ) const
{
return m_Items[ row ].m_SongId;
}
// -------------------------------------------------------------------------------- //
wxString guPLSoListBox::GetSearchText( int item ) const
{
return wxString::Format( wxT( "\"%s\" \"%s\"" ),
m_Items[ item - m_ItemsFirst ].m_ArtistName.c_str(),
m_Items[ item - m_ItemsFirst ].m_SongName.c_str() );
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::SetTracksOrder( const int order )
{
if( !m_DisableSorting )
{
if( m_TracksOrder != order )
{
m_TracksOrder = order;
if( order == wxNOT_FOUND )
m_TracksOrderDesc = false;
}
else if( order != wxNOT_FOUND )
{
m_TracksOrderDesc = !m_TracksOrderDesc;
if( !m_TracksOrderDesc )
{
m_TracksOrder = wxNOT_FOUND;
m_TracksOrderDesc = false;
}
}
int ColId = m_TracksOrder;
// Create the Columns
int CurColId;
int Count = m_ColumnNames.Count();
for( int Index = 0; Index < Count; Index++ )
{
CurColId = GetColumnId( Index );
SetColumnLabel( Index,
m_ColumnNames[ CurColId ] + ( ( ColId == CurColId ) ? ( m_TracksOrderDesc ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
}
ReloadItems();
}
}
// -------------------------------------------------------------------------------- //
void guPLSoListBox::RandomizeTracks( void )
{
int Pos;
int NewPos;
int Count = m_Items.Count();
guTrack SavedItem;
if( Count > 2 )
{
for( int Index = 0; Index < Count; Index++ )
{
do {
Pos = guRandom( Count );
NewPos = guRandom( Count );
} while( Pos == NewPos );
SavedItem = m_Items[ Pos ];
m_Items[ Pos ] = m_Items[ NewPos ];
m_Items[ NewPos ] = SavedItem;
RefreshRow( Pos );
RefreshRow( NewPos );
}
ClearSelectedItems();
}
}
}
// -------------------------------------------------------------------------------- //
| 13,953
|
C++
|
.cpp
| 380
| 30.278947
| 165
| 0.523129
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,609
|
PlayListAppend.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/playlists/PlayListAppend.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayListAppend.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guPlayListAppend::guPlayListAppend( wxWindow * parent, guDbLibrary * db, const wxArrayInt * tracks, guListItems * plitems ) :
wxDialog( parent, wxID_ANY, _( "Save to Playlist" ), wxDefaultPosition, wxSize( 387,198 ), wxDEFAULT_DIALOG_STYLE )
{
wxStaticText * PosLabel;
wxStaticText * PlayListLabel;
wxStaticText * TracksLabel;
wxStdDialogButtonSizer * StdBtnSizer;
wxButton * StdBtnSizerOK;
wxButton * StdBtnSizerCancel;
m_Db = db;
m_Tracks = tracks;
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
MainSizer->Add( 0, 20, 0, wxEXPAND, 5 );
wxFlexGridSizer * FieldsSizer = new wxFlexGridSizer( 2, 0, 0 );
FieldsSizer->AddGrowableCol( 1 );
FieldsSizer->AddGrowableRow( 2 );
FieldsSizer->SetFlexibleDirection( wxBOTH );
FieldsSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
PlayListLabel = new wxStaticText( this, wxID_ANY, _("Playlist:"), wxDefaultPosition, wxDefaultSize, 0 );
PlayListLabel->Wrap( -1 );
FieldsSizer->Add( PlayListLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
m_PlayListComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
m_PlayListItems = plitems;
int count = plitems->Count();
for( int index = 0; index < count; index++ )
{
m_PlayListComboBox->Append( plitems->Item( index ).m_Name );
}
m_PlayListComboBox->SetValue( _( "New playlist" ) );
FieldsSizer->Add( m_PlayListComboBox, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
PosLabel = new wxStaticText( this, wxID_ANY, _( "Where:" ), wxDefaultPosition, wxDefaultSize, 0 );
PosLabel->Wrap( -1 );
FieldsSizer->Add( PosLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
wxString m_PosChoiceChoices[] = { _("Beginning"), _("End") };
int m_PosChoiceNChoices = sizeof( m_PosChoiceChoices ) / sizeof( wxString );
m_PosChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_PosChoiceNChoices, m_PosChoiceChoices, 0 );
m_PosChoice->SetSelection( 1 );
FieldsSizer->Add( m_PosChoice, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
TracksLabel = new wxStaticText( this, wxID_ANY, _("Tracks:"), wxDefaultPosition, wxDefaultSize, 0 );
TracksLabel->Wrap( -1 );
FieldsSizer->Add( TracksLabel, 0, wxALL|wxALIGN_RIGHT, 5 );
m_TracksStaticText = new wxStaticText( this, wxID_ANY, wxString::Format( wxT( "%lu" ), tracks->Count() ), wxDefaultPosition, wxDefaultSize, 0 );
m_TracksStaticText->Wrap( -1 );
FieldsSizer->Add( m_TracksStaticText, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
MainSizer->Add( FieldsSizer, 1, wxEXPAND, 5 );
StdBtnSizer = new wxStdDialogButtonSizer();
StdBtnSizerOK = new wxButton( this, wxID_OK );
StdBtnSizer->AddButton( StdBtnSizerOK );
StdBtnSizerCancel = new wxButton( this, wxID_CANCEL );
StdBtnSizer->AddButton( StdBtnSizerCancel );
StdBtnSizer->SetAffirmativeButton( StdBtnSizerOK );
StdBtnSizer->SetCancelButton( StdBtnSizerCancel );
StdBtnSizer->Realize();
MainSizer->Add( StdBtnSizer, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
this->SetSizer( MainSizer );
this->Layout();
StdBtnSizerOK->SetDefault();
m_PlayListComboBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guPlayListAppend::~guPlayListAppend()
{
}
// -------------------------------------------------------------------------------- //
int guPlayListAppend::GetSelectedPosition( void )
{
return m_PosChoice->GetSelection();
}
// -------------------------------------------------------------------------------- //
int FindPlayListItem( guListItems * items, const wxString &playlistname )
{
int Count = items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( items->Item( Index ).m_Name.Lower() == playlistname )
return Index;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
int guPlayListAppend::GetSelectedPlayList( void )
{
int Selection = m_PlayListComboBox->GetSelection();
if( Selection == wxNOT_FOUND && m_PlayListComboBox->GetCount() != 0 )
{
Selection = FindPlayListItem( m_PlayListItems, m_PlayListComboBox->GetValue().Lower().Trim().Trim( false ) );
}
return Selection;
}
// -------------------------------------------------------------------------------- //
wxString guPlayListAppend::GetPlaylistName( void )
{
return m_PlayListComboBox->GetValue();
}
}
// -------------------------------------------------------------------------------- //
| 5,950
|
C++
|
.cpp
| 121
| 45.413223
| 148
| 0.605032
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,610
|
PlayListPanel.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/playlists/PlayListPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayListPanel.h"
#include "Accelerators.h"
#include "AuiNotebook.h"
#include "AuiDockArt.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "DbLibrary.h"
#include "DynamicPlayList.h"
#include "EditWithOptions.h"
#include "FileRenamer.h"
#include "Images.h"
#include "LabelEditor.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "PlayListAppend.h"
#include "PlayListFile.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Utils.h"
namespace Guayadeque {
//#define guPLAYLIST_TIMER_TEXTSEARCH 5
//#define guPLAYLIST_TIMER_TEXTSEARCH_VALUE 500
// -------------------------------------------------------------------------------- //
class guPLNamesData : public wxTreeItemData
{
private :
int m_Id;
int m_Type;
public :
guPLNamesData( const int id, const int type ) { m_Id = id; m_Type = type; };
int GetData( void ) { return m_Id; };
void SetData( int id ) { m_Id = id; };
int GetType( void ) { return m_Type; };
void SetType( int type ) { m_Type = type; };
};
BEGIN_EVENT_TABLE( guPLNamesTreeCtrl, wxTreeCtrl )
EVT_TREE_BEGIN_DRAG( wxID_ANY, guPLNamesTreeCtrl::OnBeginDrag )
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guPLNamesTreeCtrl::guPLNamesTreeCtrl( wxWindow * parent, guDbLibrary * db, guPlayListPanel * playlistpanel ) :
wxTreeCtrl( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_FULL_ROW_HIGHLIGHT|wxTR_MULTIPLE|wxNO_BORDER )
{
m_Db = db;
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_PlayListPanel = playlistpanel;
m_ImageList = new wxImageList();
m_ImageList->Add( wxBitmap( guImage( guIMAGE_INDEX_track ) ) );
m_ImageList->Add( wxBitmap( guImage( guIMAGE_INDEX_system_run ) ) );
AssignImageList( m_ImageList );
m_RootId = AddRoot( wxT( "Playlists" ), -1, -1, NULL );
m_StaticId = AppendItem( m_RootId, _( "Static playlists" ), 0, 0, NULL );
m_DynamicId = AppendItem( m_RootId, _( "Dynamic playlists" ), 1, 1, NULL );
SetIndent( 5 );
SetDropTarget( new guPLNamesDropTarget( this ) );
Bind( wxEVT_TREE_ITEM_MENU, &guPLNamesTreeCtrl::OnContextMenu, this );
Bind( wxEVT_KEY_DOWN, &guPLNamesTreeCtrl::OnKeyDown, this );
Bind( guConfigUpdatedEvent, &guPLNamesTreeCtrl::OnConfigUpdated, this, ID_CONFIG_UPDATED );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guPLNamesTreeCtrl::~guPLNamesTreeCtrl()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Unbind( wxEVT_TREE_ITEM_MENU, &guPLNamesTreeCtrl::OnContextMenu, this );
Unbind( wxEVT_KEY_DOWN, &guPLNamesTreeCtrl::OnKeyDown, this );
Unbind( guConfigUpdatedEvent, &guPLNamesTreeCtrl::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_PLAYLIST_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::ReloadItems( const bool reset )
{
wxArrayTreeItemIds SelectedItems;
wxArrayInt SelectedIds;
int SelCount = 0;
if( !reset )
{
SelCount = GetSelections( SelectedItems );
for( int Index = 0; Index < SelCount; Index++ )
{
guPLNamesData * ItemData = ( guPLNamesData * ) GetItemData( SelectedItems[ Index ] );
if( ItemData )
{
SelectedIds.Add( ItemData->GetData() );
}
}
SelectedItems.Empty();
}
DeleteChildren( m_StaticId );
DeleteChildren( m_DynamicId );
guListItems m_StaticItems;
m_Db->GetPlayLists( &m_StaticItems, guPLAYLIST_TYPE_STATIC, &m_TextSearchFilter );
int Count = m_StaticItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
wxTreeItemId NewItemId = AppendItem( m_StaticId, m_StaticItems[ Index ].m_Name, -1, -1,
new guPLNamesData( m_StaticItems[ Index ].m_Id, guPLAYLIST_TYPE_STATIC ) );
if( SelectedIds.Index( m_StaticItems[ Index ].m_Id ) != wxNOT_FOUND )
{
SelectedItems.Add( NewItemId );
}
}
}
guListItems m_DynamicItems;
m_Db->GetPlayLists( &m_DynamicItems, guPLAYLIST_TYPE_DYNAMIC, &m_TextSearchFilter );
Count = m_DynamicItems.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
wxTreeItemId NewItemId = AppendItem( m_DynamicId, m_DynamicItems[ Index ].m_Name, -1, -1,
new guPLNamesData( m_DynamicItems[ Index ].m_Id, guPLAYLIST_TYPE_DYNAMIC ) );
if( SelectedIds.Index( m_DynamicItems[ Index ].m_Id ) != wxNOT_FOUND )
{
SelectedItems.Add( NewItemId );
}
}
}
if( !reset )
{
int Count = SelectedItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
SelectItem( SelectedItems[ Index ] );
}
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnContextMenu( wxTreeEvent &event )
{
wxMenu Menu;
wxMenuItem * MenuItem;
wxPoint Point = event.GetPoint();
wxArrayTreeItemIds SelectedItems;
int SelectCount = GetSelections( SelectedItems );
wxTreeItemId ItemId = event.GetItem();
guPLNamesData * ItemData = NULL;
if( ItemId.IsOk() )
{
ItemData = ( guPLNamesData * ) GetItemData( ItemId );
if( ItemData )
{
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_PLAY, _( "Play" ), _( "Play current selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected songs to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_add ) );
Menu.Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYLIST_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYLIST_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYLIST_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu.Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
Menu.AppendSeparator();
}
}
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_NEWPLAYLIST, _( "New Dynamic Playlist" ), _( "Create a new dynamic playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_new ) );
Menu.Append( MenuItem );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_IMPORT, _( "Import" ), _( "Import a playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_new ) );
Menu.Append( MenuItem );
if( ItemData )
{
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_EXPORT, _( "Export" ), _( "Export the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu.Append( MenuItem );
Menu.AppendSeparator();
if( SelectCount == 1 )
{
if( ItemData->GetType() == guPLAYLIST_TYPE_DYNAMIC )
{
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_EDIT, _( "Edit" ), _( "Edit the selected playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_TRACKS_SAVETOPLAYLIST, _( "Save to Playlist" ), _( "Save the selected playlist as a Static Playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu.Append( MenuItem );
}
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_RENAME, _( "Rename" ), _( "Change the name of the selected playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit ) );
Menu.Append( MenuItem );
}
MenuItem = new wxMenuItem( &Menu, ID_PLAYLIST_DELETE, _( "Delete" ), _( "Delete the selected playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_edit_delete ) );
Menu.Append( MenuItem );
Menu.AppendSeparator();
MenuItem = new wxMenuItem( &Menu, ID_MAINFRAME_SET_ALLOW_PLAYLIST, _( "Set as Allow Filter" ), _( "Set this playlist as the allow filter" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_accept ) );
Menu.Append( MenuItem );
MenuItem = new wxMenuItem( &Menu, ID_MAINFRAME_SET_DENY_PLAYLIST, _( "Set as Deny Filter" ), _( "Delete the selected playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_filter ) );
Menu.Append( MenuItem );
Menu.AppendSeparator();
int TrackCount = m_PlayListPanel->GetPlaylistTrackCount();
if( TrackCount )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
MainFrame->CreateCopyToMenu( &Menu );
}
}
PopupMenu( &Menu, Point );
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnBeginDrag( wxTreeEvent &event )
{
m_DragOverItem = wxTreeItemId();
wxArrayTreeItemIds SelectedItems;
int Count = GetSelections( SelectedItems );
if( Count )
{
wxFileDataObject Files;
for( int Index = 0; Index < Count; Index++ )
{
guPLNamesData * ItemData = ( guPLNamesData * ) GetItemData( SelectedItems[ Index ] );
if( ItemData )
{
if( ItemData->GetType() == guPLAYLIST_TYPE_STATIC )
{
wxString PlayListPath = m_Db->GetPlayListPath( ItemData->GetData() );
if( !PlayListPath.IsEmpty() )
{
// If the playlist was added from a file
Files.AddFile( PlayListPath );
}
else
{
//m_Db->GetPlayListFiles( ItemData->GetData(), &Files );
guTrackArray Tracks;
//m_Db->GetPlayListSongs( ItemData->GetData(), guPLAYLIST_TYPE_STATIC, &Tracks, NULL, NULL );
//m_PLTracksListBox->GetAllSongs( &Tracks );
m_PlayListPanel->GetPlaylistTracks( &Tracks );
int Count = Tracks.Count();
if( Count )
{
guPlaylistFile PlayListFile;
for( int Index = 0; Index < Count; Index++ )
{
PlayListFile.AddItem( Tracks[ Index ].m_FileName,
Tracks[ Index ].m_ArtistName + wxT( " - " ) + Tracks[ Index ].m_SongName, Tracks[ Index ].m_Length / 1000 );
}
wxString PlayListName = m_Db->GetPlayListName( ItemData->GetData() );
PlayListFile.SetName( PlayListName );
PlayListPath = guPATH_PLAYLISTS + PlayListName + wxT( ".m3u" );
wxFileName::Mkdir( wxPathOnly( PlayListPath ), 0777, wxPATH_MKDIR_FULL );
PlayListFile.Save( PlayListPath );
m_Db->SetPlayListPath( ItemData->GetData(), PlayListPath );
Files.AddFile( PlayListPath );
}
}
}
else
{
guTrackArray Tracks;
m_Db->GetPlayListSongs( ItemData->GetData(), ItemData->GetType(), &Tracks, NULL, NULL );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
Files.AddFile( Tracks[ index ].m_FileName );
}
}
}
}
wxDropSource source( Files, this );
wxDragResult Result = source.DoDragDrop();
if( Result )
{
}
// If we left any hightligted item remove it
if( m_DragOverItem.IsOk() )
{
guLogMessage( wxT( "Clear m_DragOverItem element..."));
SetItemDropHighlight( m_DragOverItem, false );
//m_DragOverItem = wxTreeItemId();
}
}
}
// -------------------------------------------------------------------------------- //
wxDragResult guPLNamesTreeCtrl::OnDragOver( const wxCoord x, const wxCoord y )
{
int HitFlags;
wxTreeItemId TreeItemId = HitTest( wxPoint( x, y ), HitFlags );
if( TreeItemId.IsOk() )
{
if( TreeItemId != m_DragOverItem )
{
if( m_DragOverItem.IsOk() )
{
SetItemDropHighlight( m_DragOverItem, false );
}
guPLNamesData * ItemData = ( guPLNamesData * ) GetItemData( TreeItemId );
if( ItemData && ( ItemData->GetType() == guPLAYLIST_TYPE_STATIC ) )
{
SetItemDropHighlight( TreeItemId, true );
m_DragOverItem = TreeItemId;
}
}
}
else
{
if( m_DragOverItem.IsOk() )
{
SetItemDropHighlight( m_DragOverItem, false );
m_DragOverItem = wxTreeItemId();
}
}
return m_DragOverItem.IsOk() ? wxDragCopy : wxDragNone;
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnDropFile( const wxString &filename )
{
if( guPlaylistFile::IsValidPlayList( filename ) )
{
guPlaylistFile PlayList( filename );
int Count = PlayList.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
OnDropFile( PlayList.GetItem( Index ).m_Location );
}
}
}
else if( guIsValidAudioFile( filename ) )
{
if( wxFileExists( filename ) )
{
int TrackId;
if( ( TrackId = m_Db->FindTrackFile( filename, NULL ) ) )
{
m_DropIds.Add( TrackId );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnDropTracks( const guTrackArray * tracks )
{
if( tracks )
{
int Count = tracks->Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
const guTrack &Track = tracks->Item( Index );
if( Track.m_MediaViewer == m_PlayListPanel->m_MediaViewer )
{
m_DropIds.Add( Track.m_SongId );
}
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnDropEnd( void )
{
if( m_DragOverItem.IsOk() )
{
SetItemDropHighlight( m_DragOverItem, false );
if( m_DropIds.Count() )
{
guPLNamesData * ItemData = ( guPLNamesData * ) GetItemData( m_DragOverItem );
if( ItemData && ( ItemData->GetType() == guPLAYLIST_TYPE_STATIC ) )
{
m_Db->AppendStaticPlayList( ItemData->GetData(), m_DropIds );
m_Db->UpdateStaticPlayListFile( ItemData->GetData() );
}
SelectItem( m_StaticId );
SelectItem( m_DragOverItem );
}
m_DragOverItem = wxTreeItemId();
}
else
{
guLogMessage( wxT( "Not set item where was dragged..." ) );
}
m_DropIds.Clear();
}
// -------------------------------------------------------------------------------- //
void guPLNamesTreeCtrl::OnKeyDown( wxKeyEvent &event )
{
if( event.GetKeyCode() == WXK_DELETE )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_PLAYLIST_DELETE );
wxPostEvent( this, CmdEvent );
return;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
// guPLNamesDropFilesThread
// -------------------------------------------------------------------------------- //
guPLNamesDropFilesThread::guPLNamesDropFilesThread( guPLNamesDropTarget * plnamesdroptarget,
guPLNamesTreeCtrl * plnamestreectrl, const wxArrayString &files ) :
wxThread()
{
m_PLNamesTreeCtrl = plnamestreectrl;
m_Files = files;
m_PLNamesDropTarget = plnamesdroptarget;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY );
Run();
}
}
// -------------------------------------------------------------------------------- //
guPLNamesDropFilesThread::~guPLNamesDropFilesThread()
{
// printf( "guPLNamesDropFilesThread Object destroyed\n" );
if( !TestDestroy() )
{
m_PLNamesDropTarget->ClearPlayListFilesThread();
}
}
// -------------------------------------------------------------------------------- //
void guPLNamesDropFilesThread::AddDropFiles( const wxString &DirName )
{
wxDir Dir;
wxString FileName;
wxString SavedDir( wxGetCwd() );
//printf( "Entering Dir : " ); printf( ( char * ) DirName.char_str() ); ; printf( "\n" );
if( wxDirExists( DirName ) )
{
//wxMessageBox( DirName, wxT( "DirName" ) );
Dir.Open( DirName );
wxSetWorkingDirectory( DirName );
if( Dir.IsOpened() )
{
if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( ( FileName[ 0 ] != '.' ) )
{
if( Dir.Exists( FileName ) )
{
AddDropFiles( DirName + wxT( "/" ) + FileName );
}
else
{
m_PLNamesTreeCtrl->OnDropFile( DirName + wxT( "/" ) + FileName );
}
}
} while( Dir.GetNext( &FileName ) && !TestDestroy() );
}
}
}
else
{
m_PLNamesTreeCtrl->OnDropFile( DirName );
}
wxSetWorkingDirectory( SavedDir );
}
// -------------------------------------------------------------------------------- //
guPLNamesDropFilesThread::ExitCode guPLNamesDropFilesThread::Entry()
{
int Count = m_Files.Count();
for( int index = 0; index < Count; ++index )
{
if( TestDestroy() )
break;
AddDropFiles( m_Files[ index ] );
}
if( !TestDestroy() )
{
//
m_PLNamesTreeCtrl->OnDropEnd();
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guPLNamesDropTarget
// -------------------------------------------------------------------------------- //
guPLNamesDropTarget::guPLNamesDropTarget( guPLNamesTreeCtrl * plnamestreectrl ) : wxDropTarget()
{
m_PLNamesTreeCtrl = plnamestreectrl;
m_PLNamesDropFilesThread = NULL;
wxDataObjectComposite * DataObject = new wxDataObjectComposite();
wxCustomDataObject * TracksDataObject = new wxCustomDataObject( wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) );
DataObject->Add( TracksDataObject, true );
wxFileDataObject * FileDataObject = new wxFileDataObject();
DataObject->Add( FileDataObject, false );
SetDataObject( DataObject );
}
// -------------------------------------------------------------------------------- //
guPLNamesDropTarget::~guPLNamesDropTarget()
{
// printf( "guPLNamesDropTarget Object destroyed\n" );
}
// -------------------------------------------------------------------------------- //
bool guPLNamesDropTarget::OnDrop( wxCoord x, wxCoord y )
{
return true;
}
// -------------------------------------------------------------------------------- //
wxDragResult guPLNamesDropTarget::OnData( wxCoord x, wxCoord y, wxDragResult def )
{
//guLogMessage( wxT( "guListViewDropTarget::OnData" ) );
if( def == wxDragError || def == wxDragNone || def == wxDragCancel )
return def;
if( !GetData() )
{
guLogMessage( wxT( "Error getting drop data" ) );
return wxDragError;
}
guDataObjectComposite * DataObject = ( guDataObjectComposite * ) m_dataObject;
wxDataFormat ReceivedFormat = DataObject->GetReceivedFormat();
//guLogMessage( wxT( "ReceivedFormat: '%s'" ), ReceivedFormat.GetId().c_str() );
if( ReceivedFormat == wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) )
{
guTrackArray * Tracks;
if( !DataObject->GetDataHere( ReceivedFormat, &Tracks ) )
{
guLogMessage( wxT( "Error getting tracks data..." ) );
}
else
{
m_PLNamesTreeCtrl->OnDropTracks( Tracks );
m_PLNamesTreeCtrl->OnDropEnd();
// if( Tracks )
// delete Tracks;
}
}
else if( ReceivedFormat == wxDataFormat( wxDF_FILENAME ) )
{
if( m_PLNamesDropFilesThread )
{
m_PLNamesDropFilesThread->Pause();
m_PLNamesDropFilesThread->Delete();
}
wxFileDataObject * FileDataObject = ( wxFileDataObject * ) DataObject->GetDataObject( wxDataFormat( wxDF_FILENAME ) );
if( FileDataObject )
{
m_PLNamesDropFilesThread = new guPLNamesDropFilesThread( this, m_PLNamesTreeCtrl, FileDataObject->GetFilenames() );
if( !m_PLNamesDropFilesThread )
{
guLogError( wxT( "Could not create the add files thread." ) );
}
}
}
return def;
}
// -------------------------------------------------------------------------------- //
wxDragResult guPLNamesDropTarget::OnDragOver( wxCoord x, wxCoord y, wxDragResult def )
{
//printf( "guPLNamesDropTarget::OnDragOver... %d - %d\n", x, y );
return m_PLNamesTreeCtrl->OnDragOver( x, y );
}
// -------------------------------------------------------------------------------- //
// guPlayListPanel
// -------------------------------------------------------------------------------- //
guPlayListPanel::guPlayListPanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guAuiManagerPanel( parent )
{
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_PlayerPanel = mediaviewer->GetPlayerPanel();
m_ConfigPath = mediaviewer->ConfigPath() + wxT( "/playlists" );
m_ExportLastFolder = wxGetHomeDir();
m_LockSelection = false;
guConfig * Config = ( guConfig * ) guConfig::Get();
m_VisiblePanels = Config->ReadNum( wxT( "VisiblePanels" ), guPANEL_PLAYLIST_VISIBLE_DEFAULT, m_ConfigPath );
InitPanelData();
CreateControls();
}
// -------------------------------------------------------------------------------- //
guPlayListPanel::~guPlayListPanel()
{
// Save the Splitter positions into the main config
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteNum( wxT( "VisiblePanels" ), m_VisiblePanels, m_ConfigPath );
Config->WriteStr( wxT( "LastLayout" ), m_AuiManager.SavePerspective(), m_ConfigPath );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::CreateControls( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPanel * NamesPanel;
NamesPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * NameSizer;
NameSizer = new wxBoxSizer( wxVERTICAL );
m_NamesTreeCtrl = new guPLNamesTreeCtrl( NamesPanel, m_Db, this );
m_NamesTreeCtrl->ExpandAll();
NameSizer->Add( m_NamesTreeCtrl, 1, wxEXPAND, 5 );
NamesPanel->SetSizer( NameSizer );
NamesPanel->Layout();
NameSizer->Fit( NamesPanel );
m_AuiManager.AddPane( NamesPanel,
wxAuiPaneInfo().Name( wxT( "PlayListNames" ) ).Caption( _( "Playlists" ) ).
MinSize( 50, 50 ).CloseButton( false ).
Dockable( true ).Left() );
wxPanel * DetailsPanel;
DetailsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * DetailsSizer;
DetailsSizer = new wxBoxSizer( wxVERTICAL );
m_PLTracksListBox = new guPLSoListBox( DetailsPanel, m_MediaViewer, m_ConfigPath, guLISTVIEW_COLUMN_SELECT );
DetailsSizer->Add( m_PLTracksListBox, 1, wxEXPAND, 5 );
DetailsPanel->SetSizer( DetailsSizer );
DetailsPanel->Layout();
DetailsSizer->Fit( DetailsPanel );
m_AuiManager.AddPane( DetailsPanel, wxAuiPaneInfo().Name( wxT( "PlayListTracks" ) ).Caption( wxT( "PlayList" ) ).
MinSize( 50, 50 ).
CenterPane() );
wxString PlayListLayout = Config->ReadStr( wxT( "LastLayout" ), wxEmptyString, m_ConfigPath );
if( Config->GetIgnoreLayouts() || PlayListLayout.IsEmpty() )
{
m_VisiblePanels = guPANEL_PLAYLIST_VISIBLE_DEFAULT;
//m_AuiManager.Update();
PlayListLayout = wxT( "layout2|name=PlayListNames;caption=" ) + wxString( _( "Playlists" ) );
PlayListLayout += wxT( ";state=2044;dir=4;layer=0;row=0;pos=0;prop=100000;bestw=180;besth=350;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
PlayListLayout += wxT( "name=PlayListTracks;caption=Playlists;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
PlayListLayout += wxT( "dock_size(1,2,0)=47|dock_size(4,0,0)=186|dock_size(5,0,0)=52|" );
}
m_AuiManager.LoadPerspective( PlayListLayout, true );
Bind( wxEVT_TREE_SEL_CHANGED, &guPlayListPanel::OnPLNamesSelected, this );
Bind( wxEVT_TREE_ITEM_ACTIVATED, &guPlayListPanel::OnPLNamesActivated, this );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesPlay, this, ID_PLAYLIST_PLAY );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesEnqueue, this, ID_PLAYLIST_ENQUEUE_AFTER_ALL, ID_PLAYLIST_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesNewPlaylist, this, ID_PLAYLIST_NEWPLAYLIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesEditPlaylist, this, ID_PLAYLIST_EDIT );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesRenamePlaylist, this, ID_PLAYLIST_RENAME );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesDeletePlaylist, this, ID_PLAYLIST_DELETE );
m_NamesTreeCtrl->Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesCopyTo, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesImport, this, ID_PLAYLIST_IMPORT );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLNamesExport, this, ID_PLAYLIST_EXPORT );
Bind( wxEVT_MENU, &guPlayListPanel::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_ALLOW_PLAYLIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnSetAllowDenyFilter, this, ID_MAINFRAME_SET_DENY_PLAYLIST );
m_PLTracksListBox->Bind( wxEVT_LISTBOX_DCLICK, &guPlayListPanel::OnPLTracksActivated, this );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksDeleteClicked, this, ID_TRACKS_DELETE );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksDeleteLibrary, this, ID_TRACKS_DELETE_LIBRARY );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksDeleteDrive, this, ID_TRACKS_DELETE_DRIVE );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksPlayClicked, this, ID_TRACKS_PLAY );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksQueueClicked, this, ID_TRACKS_ENQUEUE_AFTER_ALL, ID_TRACKS_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksEditLabelsClicked, this, ID_TRACKS_EDITLABELS );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksEditTracksClicked, this, ID_TRACKS_EDITTRACKS );
m_PLTracksListBox->Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSavePlayListClicked, this, ID_TRACKS_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSetRating, this, ID_TRACKS_SET_RATING_0, ID_TRACKS_SET_RATING_5 );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSetField, this, ID_TRACKS_SET_COLUMN );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksEditField, this, ID_TRACKS_EDIT_COLUMN );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSelectGenre, this, ID_TRACKS_BROWSE_GENRE );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSelectArtist, this, ID_TRACKS_BROWSE_ARTIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSelectAlbumArtist, this, ID_TRACKS_BROWSE_ALBUMARTIST );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSelectAlbum, this, ID_TRACKS_BROWSE_ALBUM );
Bind( wxEVT_MENU, &guPlayListPanel::OnPLTracksSelectComposer, this, ID_TRACKS_BROWSE_COMPOSER );
Bind( wxEVT_MENU, &guPlayListPanel::OnGoToSearch, this, ID_PLAYLIST_SEARCH );
m_PLTracksListBox->Bind( wxEVT_LIST_COL_CLICK, &guPlayListPanel::OnPLTracksColClicked, this );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::InitPanelData()
{
}
// -------------------------------------------------------------------------------- //
bool guPlayListPanel::DoTextSearch( const wxString &textsearch )
{
if( m_LastSearchString != textsearch )
{
m_LastSearchString = textsearch; //m_InputTextCtrl->GetValue();
if( !m_LastSearchString.IsEmpty() )
{
if( m_LastSearchString.Length() > 0 )
{
m_NamesTreeCtrl->m_TextSearchFilter = guSplitWords( m_LastSearchString );
m_NamesTreeCtrl->ExpandAll();
m_NamesTreeCtrl->ReloadItems();
}
return true;
}
else
{
m_NamesTreeCtrl->m_TextSearchFilter.Clear();
m_NamesTreeCtrl->ExpandAll();
m_NamesTreeCtrl->ReloadItems();
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesSelected( wxTreeEvent& event )
{
if( m_LockSelection )
return;
if( m_LastSelectedItem != event.GetItem() )
{
m_LastSelectedItem = event.GetItem();
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( m_LastSelectedItem );
if( ItemData )
{
if( ItemData->GetType() == guPLAYLIST_TYPE_DYNAMIC )
{
// guDynPlayList DynPlayList;
// m_Db->GetDynamicPlayList( ItemData->GetData(), &DynPlayList );
// if( DynPlayList.m_Sorted )
// SetTracksOrder( wxNOT_FOUND, false );
m_PLTracksListBox->SetPlayList( ItemData->GetData(), ItemData->GetType() );
m_LockSelection = true;
m_NamesTreeCtrl->UnselectAll();
m_NamesTreeCtrl->SelectItem( m_LastSelectedItem );
m_LockSelection = false;
}
else
{
wxArrayTreeItemIds Selections;
m_NamesTreeCtrl->GetSelections( Selections );
wxArrayInt Ids;
wxArrayInt Types;
int Count = Selections.Count();
for( int Index = 0; Index < Count; Index++ )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( Selections[ Index ] );
if( ItemData && ( ItemData->GetType() == guPLAYLIST_TYPE_STATIC ) )
{
Ids.Add( ItemData->GetData() );
Types.Add( ItemData->GetType() );
}
else
{
m_LockSelection = true;
m_NamesTreeCtrl->SelectItem( Selections[ Index ], false );
m_LockSelection = false;
}
}
m_PLTracksListBox->SetPlayList( Ids, Types );
}
}
else
{
m_PLTracksListBox->SetPlayList( -1, -1 );
m_LockSelection = true;
m_NamesTreeCtrl->UnselectAll();
m_NamesTreeCtrl->SelectItem( m_LastSelectedItem );
m_LockSelection = false;
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesActivated( wxTreeEvent& event )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( event.GetItem() );
if( ItemData )
{
guTrackArray Tracks;
m_PLTracksListBox->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Tracks );
}
else
{
m_PlayerPanel->SetPlayList( Tracks );
}
}
}
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesPlay( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guTrackArray Tracks;
m_PLTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->SetPlayList( Tracks );
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesEnqueue( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guTrackArray Tracks;
m_PLTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->AddToPlayList( Tracks, true, event.GetId() - ID_PLAYLIST_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesNewPlaylist( wxCommandEvent &event )
{
guDynPlayList DynPlayList;
guDynPlayListEditor * PlayListEditor = new guDynPlayListEditor( this, &DynPlayList );
if( PlayListEditor->ShowModal() == wxID_OK )
{
PlayListEditor->FillPlayListEditData();
m_Db->CreateDynamicPlayList( DynPlayList.m_Name, &DynPlayList );
SendPlayListUpdatedEvent();
}
PlayListEditor->Destroy();
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesEditPlaylist( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
guDynPlayList DynPlayList;
m_Db->GetDynamicPlayList( ItemData->GetData(), &DynPlayList );
guDynPlayListEditor * PlayListEditor = new guDynPlayListEditor( this, &DynPlayList );
if( PlayListEditor->ShowModal() == wxID_OK )
{
PlayListEditor->FillPlayListEditData();
m_Db->UpdateDynamicPlayList( ItemData->GetData(), &DynPlayList );
m_NamesTreeCtrl->ReloadItems( false );
}
PlayListEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesRenamePlaylist( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Playlist Name: " ),
_( "Enter the new playlist name" ), m_NamesTreeCtrl->GetItemText( ItemId ) );
if( EntryDialog->ShowModal() == wxID_OK )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
wxASSERT( ItemData );
m_Db->SetPlayListName( ItemData->GetData(), EntryDialog->GetValue() );
if( ItemData->GetType() == guPLAYLIST_TYPE_STATIC )
m_Db->UpdateStaticPlayListFile( ItemData->GetData() );
//m_NamesTreeCtrl->SetItemText( ItemId, EntryDialog->GetValue() );
SendPlayListUpdatedEvent();
}
EntryDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::DeleteCurrentPlayList( void )
{
wxArrayTreeItemIds SelectedItems;
int Count = m_NamesTreeCtrl->GetSelections( SelectedItems );
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( SelectedItems[ Index ] );
if( ItemData )
{
m_Db->DeletePlayList( ItemData->GetData() );
if( ItemData->GetType() == guPLAYLIST_TYPE_STATIC )
m_Db->UpdateStaticPlayListFile( ItemData->GetData() );
}
}
SendPlayListUpdatedEvent();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesDeletePlaylist( wxCommandEvent &event )
{
if( wxMessageBox( _( "Are you sure to delete the selected Playlist?" ),
_( "Confirm" ),
wxICON_QUESTION|wxYES_NO|wxNO_DEFAULT, this ) == wxYES )
{
DeleteCurrentPlayList();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesCopyTo( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetInt( Index );
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
if( ItemData )
{
wxString PlayListPath = m_Db->GetPlayListPath( ItemData->GetData() );
if( !PlayListPath.IsEmpty() )
{
event.SetId( ID_MAINFRAME_COPYTODEVICE_PLAYLIST );
event.SetClientData( new wxString( PlayListPath ) );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
else
{
guTrackArray Tracks;
m_PLTracksListBox->GetAllSongs( &Tracks );
int Count = Tracks.Count();
if( Count )
{
guPlaylistFile PlayListFile;
NormalizeTracks( &Tracks );
for( int Index = 0; Index < Count; Index++ )
{
PlayListFile.AddItem( Tracks[ Index ].m_FileName,
Tracks[ Index ].m_ArtistName + wxT( " - " ) + Tracks[ Index ].m_SongName );
}
wxString PlayListName = m_NamesTreeCtrl->GetItemText( ItemId );
PlayListFile.SetName( PlayListName );
PlayListPath = wxGetHomeDir() + wxT( "/.guayadeque/PlayLists/") + PlayListName + wxT( ".m3u" );
wxFileName::Mkdir( wxPathOnly( PlayListPath ), 0777, wxPATH_MKDIR_FULL );
PlayListFile.Save( PlayListPath );
m_Db->SetPlayListPath( ItemData->GetData(), PlayListPath );
event.SetId( ID_MAINFRAME_COPYTODEVICE_PLAYLIST );
event.SetClientData( new wxString( PlayListPath ) );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
}
}
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
guTrackArray * Tracks = new guTrackArray();
m_PLTracksListBox->GetAllSongs( Tracks );
NormalizeTracks( Tracks );
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesImport( wxCommandEvent &event )
{
wxFileDialog * FileDialog = new wxFileDialog( this,
_( "Select the playlist file" ),
wxGetHomeDir(),
wxEmptyString,
wxT( "*.m3u;*.pls;*.asx;*.xspf" ),
wxFD_OPEN | wxFD_FILE_MUST_EXIST );
if( FileDialog )
{
if( FileDialog->ShowModal() == wxID_OK )
{
guPlaylistFile PlayListFile( FileDialog->GetPath() );
int Count = PlayListFile.Count();
if( Count )
{
if( PlayListFile.GetName().IsEmpty() )
{
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Playlist Name: " ),
_( "Enter the new playlist name" ), FileDialog->GetPath().AfterLast( wxT( '/' ) ).BeforeLast( wxT( '.' ) ) );
if( EntryDialog->ShowModal() == wxID_OK )
{
PlayListFile.SetName( EntryDialog->GetValue() );
}
delete EntryDialog;
}
//
if( PlayListFile.GetName().IsEmpty() )
{
PlayListFile.SetName( _( "New Playlist" ) );
}
wxArrayInt Songs;
for( int Index = 0; Index < Count; Index++ )
{
//wxURI Uri( PlayListFile.GetItem( Index ).m_Location );
//wxString FileName = Uri.BuildUnescapedURI();
wxString FileName = PlayListFile.GetItem( Index ).m_Location;
if( FileName.StartsWith( wxT( "file:" ) ) )
FileName = FileName.Mid( 5 );
//guLogMessage( wxT( "Trying to add file '%s'" ), FileName.c_str() );
int SongId = m_Db->FindTrackFile( FileName, NULL );
if( SongId )
{
Songs.Add( SongId );
//guLogMessage( wxT( "Found it!" ) );
}
//else
// guLogMessage( wxT( "Not Found it!" ) );
}
if( Songs.Count() )
{
int PLId = m_Db->CreateStaticPlayList( PlayListFile.GetName(), Songs );
m_Db->UpdateStaticPlayListFile( PLId );
}
//m_NamesTreeCtrl->ReloadItems();
SendPlayListUpdatedEvent();
}
}
FileDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLNamesExport( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
wxString PlayListName = m_NamesTreeCtrl->GetItemText( ItemId );
wxFileDialog * FileDialog = new wxFileDialog( this,
_( "Select the playlist file" ),
m_ExportLastFolder,
PlayListName + wxT( ".m3u" ),
wxT( "*.m3u;*.pls;*.asx;*.xspf" ),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
if( FileDialog )
{
if( FileDialog->ShowModal() == wxID_OK )
{
guPlaylistFile PlayListFile;
PlayListFile.SetName( PlayListName );
guTrackArray Tracks;
m_PLTracksListBox->GetAllSongs( &Tracks );
int Count = Tracks.Count();
if( Count )
{
NormalizeTracks( &Tracks );
for( int Index = 0; Index < Count; Index++ )
{
PlayListFile.AddItem( Tracks[ Index ].m_FileName,
Tracks[ Index ].m_ArtistName + wxT( " - " ) + Tracks[ Index ].m_SongName );
}
PlayListFile.Save( FileDialog->GetPath() );
}
}
m_ExportLastFolder = wxPathOnly( FileDialog->GetPath() );
FileDialog->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksActivated( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
if( Tracks.Count() )
{
NormalizeTracks( &Tracks );
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Tracks );
}
else
{
m_PlayerPanel->SetPlayList( Tracks );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksDeleteClicked( wxCommandEvent &event )
{
wxArrayInt DelTracks;
m_PLTracksListBox->GetPlayListSetIds( &DelTracks );
if( DelTracks.Count() )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
if( ItemData && ItemData->GetType() == guPLAYLIST_TYPE_STATIC )
{
m_Db->DelPlaylistSetIds( ItemData->GetData(), DelTracks );
m_Db->UpdateStaticPlayListFile( ItemData->GetData() );
//m_PLTracksListBox->ReloadItems( false );
SendPlayListUpdatedEvent();
}
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksPlayClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
m_PLTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->SetPlayList( Tracks );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksQueueClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
m_PLTracksListBox->GetAllSongs( &Tracks );
NormalizeTracks( &Tracks );
m_PlayerPanel->AddToPlayList( Tracks, true, event.GetId() - ID_TRACKS_ENQUEUE_AFTER_ALL );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksEditLabelsClicked( wxCommandEvent &event )
{
guListItems Tracks;
m_PLTracksListBox->GetSelectedItems( &Tracks, false );
if( Tracks.Count() )
{
guArrayListItems LabelSets = m_Db->GetSongsLabels( m_PLTracksListBox->GetSelectedItems( false ) );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Tracks Labels Editor" ), false, &Tracks, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the files
m_Db->UpdateSongsLabels( LabelSets );
}
LabelEditor->Destroy();
m_LockSelection = true;
m_PLTracksListBox->ReloadItems( false );
m_LockSelection = false;
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &Tracks, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
m_MediaViewer->UpdateTracks( Tracks, Images, Lyrics, ChangedFlags );
// m_LockSelection = true;
// m_PLTracksListBox->ReloadItems( false );
// m_LockSelection = false;
// Update the track in database, playlist, etc
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_MEDIAVIEWER, &Tracks );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_PLTracksListBox->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
else
{
m_PLTracksListBox->GetAllSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
if( NewSongs.Count() )
{
guListItems PlayLists;
m_Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( guMainFrame::GetMainFrame(), m_Db, &NewSongs, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == wxNOT_FOUND )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
int PLId = m_Db->CreateStaticPlayList( PLName, NewSongs );
m_Db->UpdateStaticPlayListFile( PLId );
}
else
{
int PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
m_Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
m_Db->UpdateStaticPlayList( PLId, NewSongs );
m_Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
m_Db->AppendStaticPlayList( PLId, NewSongs );
}
m_Db->UpdateStaticPlayListFile( PLId );
}
SendPlayListUpdatedEvent();
}
PlayListAppendDlg->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSetRating( wxCommandEvent &event )
{
int Rating = event.GetId() - ID_TRACKS_SET_RATING_0;
//guLogMessage( wxT( "OnSongSetRating( %i )" ), Rating );
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
m_MediaViewer->SetTracksRating( Tracks, Rating );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSetField( wxCommandEvent &event )
{
int ColumnId = m_PLTracksListBox->GetColumnId( m_PLTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guPlayListPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxVariant NewData = m_PLTracksListBox->GetLastDataClicked();
//guLogMessage( wxT( "Setting Data to : %s" ), NewData.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = NewData.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = NewData.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = NewData.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = NewData.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = NewData.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = NewData.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = NewData.GetLong();
break;
}
}
m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksEditField( wxCommandEvent &event )
{
int ColumnId = m_PLTracksListBox->GetColumnId( m_PLTracksListBox->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxString Label = m_PLTracksListBox->GetColumnNames()[ ColumnId ];
wxVariant DefValue = m_PLTracksListBox->GetLastDataClicked();
wxArrayString Items;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxVariant Value;
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Value = ( long ) Track->m_Number;
break;
case guSONGS_COLUMN_TITLE :
Value = Track->m_SongName;
break;
case guSONGS_COLUMN_ARTIST :
Value = Track->m_ArtistName;
break;
case guSONGS_COLUMN_ALBUMARTIST :
Value = Track->m_AlbumArtist;
break;
case guSONGS_COLUMN_ALBUM :
Value = Track->m_AlbumName;
break;
case guSONGS_COLUMN_GENRE :
Value = Track->m_GenreName;
break;
case guSONGS_COLUMN_COMPOSER :
Value = Track->m_Composer;
break;
case guSONGS_COLUMN_DISK :
Value = Track->m_Disk;
break;
case guSONGS_COLUMN_YEAR :
Value = ( long ) Track->m_Year;
break;
}
if( Items.Index( Value.GetString() ) == wxNOT_FOUND )
Items.Add( Value.GetString() );
}
guEditWithOptions * FieldEditor = new guEditWithOptions( this, _( "Field Editor" ), Label, DefValue.GetString(), Items );
if( FieldEditor )
{
if( FieldEditor->ShowModal() == wxID_OK )
{
DefValue = FieldEditor->GetData();
//guLogMessage( wxT( "Setting Data to : %s" ), DefValue.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = DefValue.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = DefValue.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = DefValue.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = DefValue.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = DefValue.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = DefValue.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = DefValue.GetLong();
break;
}
}
m_Db->UpdateSongs( &Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
FieldEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::PlayListUpdated( void )
{
//guLogMessage( wxT( "guPLayListPanel::PlayListUpdated" ) );
m_LockSelection = true;
m_NamesTreeCtrl->ReloadItems( false );
m_LockSelection = false;
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSelectGenre( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Genres = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Genres->Index( Tracks[ index ].m_GenreId ) == wxNOT_FOUND )
{
Genres->Add( Tracks[ index ].m_GenreId );
}
}
event.SetId( ID_GENRE_SETSELECTION );
event.SetClientData( ( void * ) Genres );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSelectArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Artists = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Artists->Index( Tracks[ index ].m_ArtistId ) == wxNOT_FOUND )
{
Artists->Add( Tracks[ index ].m_ArtistId );
}
}
event.SetId( ID_ARTIST_SETSELECTION );
event.SetClientData( ( void * ) Artists );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSelectAlbumArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Ids = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Ids->Index( Tracks[ index ].m_AlbumArtistId ) == wxNOT_FOUND )
{
Ids->Add( Tracks[ index ].m_AlbumArtistId );
}
}
event.SetId( ID_ALBUMARTIST_SETSELECTION );
event.SetClientData( ( void * ) Ids );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSelectAlbum( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Albums = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Albums->Index( Tracks[ index ].m_AlbumId ) == wxNOT_FOUND )
{
Albums->Add( Tracks[ index ].m_AlbumId );
}
}
event.SetId( ID_ALBUM_SETSELECTION );
event.SetClientData( ( void * ) Albums );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksSelectComposer( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
wxArrayInt * Composers = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Composers->Index( Tracks[ index ].m_ComposerId ) == wxNOT_FOUND )
{
Composers->Add( Tracks[ index ].m_ComposerId );
}
}
event.SetId( ID_COMPOSER_SETSELECTION );
event.SetClientData( ( void * ) Composers );
wxPostEvent( m_MediaViewer, event );
}
// -------------------------------------------------------------------------------- //
bool guPlayListPanel::GetPlayListCounters( wxLongLong * count, wxLongLong * len, wxLongLong * size )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
if( ItemData )
{
// m_Db->GetPlayListCounters( ItemData->GetData(), ItemData->GetType(), count, len, size );
m_PLTracksListBox->GetCounters( count, len, size );
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksDeleteLibrary( wxCommandEvent &event )
{
if( m_PLTracksListBox->GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to remove the selected tracks from your library?" ),
wxT( "Remove tracks from library" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
//
m_Db->DeleteLibraryTracks( &Tracks, true );
//
m_PLTracksListBox->ClearSelectedItems();
//m_PLTracksListBox->ReloadItems();
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_MEDIAVIEWER, &Tracks );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksDeleteDrive( wxCommandEvent &event )
{
if( m_PLTracksListBox->GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to delete the selected tracks from your drive?\nThis will permanently erase the selected tracks." ),
wxT( "Remove tracks from drive" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_PLTracksListBox->GetSelectedSongs( &Tracks );
//
m_MediaViewer->DeleteTracks( &Tracks );
//
m_PLTracksListBox->ClearSelectedItems();
SendPlayListUpdatedEvent();
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::SendPlayListUpdatedEvent( void )
{
m_MediaViewer->UpdatePlaylists();
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnGoToSearch( wxCommandEvent &event )
{
m_MediaViewer->GoToSearch();
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnSetAllowDenyFilter( wxCommandEvent &event )
{
wxTreeItemId ItemId = m_NamesTreeCtrl->GetFocusedItem();
if( ItemId.IsOk() )
{
guPLNamesData * ItemData = ( guPLNamesData * ) m_NamesTreeCtrl->GetItemData( ItemId );
if( ItemData )
{
event.SetInt( ItemData->GetData() );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
}
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
if( m_MediaViewer )
m_MediaViewer->NormalizeTracks( tracks, isdrag );
}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::UpdatePlaylists( void )
{
m_LockSelection = true;
m_NamesTreeCtrl->ReloadItems( false );
m_PLTracksListBox->ReloadItems( false );
m_LockSelection = false;
m_MediaViewer->PlayListUpdated();
}
//// -------------------------------------------------------------------------------- //
//void guPlayListPanel::SetTracksOrder( const int order, const int reload )
//{
// m_PLTracksListBox->SetTracksOrder( order );
//
// int ColId = m_PLTracksListBox->GetTracksOrder();
//
// // Create the Columns
// wxArrayString ColumnNames = m_PLTracksListBox->GetColumnNames();
// int CurColId;
// int count = ColumnNames.Count();
// for( int index = 0; index < count; index++ )
// {
// CurColId = m_PLTracksListBox->GetColumnId( index );
// m_PLTracksListBox->SetColumnLabel( index,
// ColumnNames[ CurColId ] + ( ( ColId == CurColId ) ? ( m_PLTracksListBox->GetTracksOrderDesc() ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
// }
//
// if( reload )
// m_PLTracksListBox->ReloadItems();
//}
// -------------------------------------------------------------------------------- //
void guPlayListPanel::OnPLTracksColClicked( wxListEvent &event )
{
int ColId = m_PLTracksListBox->GetColumnId( event.m_col );
m_PLTracksListBox->SetTracksOrder( ColId );
}
}
// -------------------------------------------------------------------------------- //
| 70,278
|
C++
|
.cpp
| 1,662
| 33.158845
| 212
| 0.538096
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,611
|
PlayListFile.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/playlists/PlayListFile.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PlayListFile.h"
#include "Utils.h"
#include "TagInfo.h"
#include <wx/arrimpl.cpp>
#include <wx/fileconf.h>
#include <wx/filename.h>
#include <wx/sstream.h>
#include <wx/tokenzr.h>
#include <wx/uri.h>
#include <wx/wfstream.h>
#include <wx/xml/xml.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guPlaylistItemArray )
WX_DEFINE_OBJARRAY( guCuePlaylistItemArray )
// -------------------------------------------------------------------------------- //
// guPlaylistItem
// -------------------------------------------------------------------------------- //
wxString guPlaylistItem::GetLocation( const bool relative, const wxString &pathbase )
{
if( relative )
{
wxFileName FileName( m_Location );
if( FileName.MakeRelativeTo( pathbase ) )
{
return FileName.GetFullPath();
}
}
return m_Location;
}
// -------------------------------------------------------------------------------- //
guPlaylistFile::guPlaylistFile( const wxString &uri )
{
if( !uri.IsEmpty() )
Load( uri );
}
// -------------------------------------------------------------------------------- //
guPlaylistFile::~guPlaylistFile()
{
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::IsValidPlayList( const wxString &uri )
{
wxURI Uri( uri );
wxString PLPath = Uri.GetPath().Lower();
return PLPath.EndsWith( wxT( ".pls" ) ) ||
PLPath.EndsWith( wxT( ".m3u" ) ) ||
PLPath.EndsWith( wxT( ".m3u8" ) ) ||
PLPath.EndsWith( wxT( ".xspf" ) ) ||
PLPath.EndsWith( wxT( ".asx" ) );
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::Load( const wxString &uri )
{
guLogMessage( wxT( "guPlaylistFile::Load '%s'" ), uri.c_str() );
wxURI Uri( uri );
wxString LowerPath = Uri.GetPath().Lower();
//guLogMessage( wxT( "'%s' IsReference:%i" ), uri.c_str(), Uri.IsReference() );
if( Uri.IsReference() )
{
wxString FileName;
if( uri.StartsWith( wxT( "file://" ) ) )
{
FileName = wxURI::Unescape( Uri.GetPath() );
}
else
{
FileName = uri;
}
if( LowerPath.EndsWith( wxT( ".pls" ) ) )
{
return ReadPlsFile( FileName );
}
else if( LowerPath.EndsWith( wxT( ".m3u" ) ) || LowerPath.EndsWith( wxT( ".m3u8" ) ) )
{
return ReadM3uFile( FileName );
}
else if( LowerPath.EndsWith( wxT( ".xspf" ) ) )
{
return ReadXspfFile( FileName );
}
else if( LowerPath.EndsWith( wxT( ".asx" ) ) )
{
return ReadAsxFile( FileName );
}
}
else
{
if( LowerPath.EndsWith( wxT( ".ashx" ) ) )
{
wxString Content = GetUrlContent( uri );
guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
wxArrayString PlaylistItems = wxStringTokenize( Content, wxT( "\n" ) );
int Count = PlaylistItems.Count();
for( int Index = 0; Index < Count; Index++ )
{
Load( PlaylistItems[ Index ] );
}
}
else if( !IsValidPlayList( LowerPath ) )
{
m_Playlist.Add( new guPlaylistItem( uri, uri ) );
return true;
}
else
{
guLogMessage( wxT( "Trying to get the uri: %s" ), uri.c_str() );
wxString Content = GetUrlContent( uri );
if( !Content.IsEmpty() )
{
wxStringInputStream Ins( Content );
if( LowerPath.EndsWith( wxT( ".pls" ) ) )
{
return ReadPlsStream( Ins );
}
else if( LowerPath.EndsWith( wxT( ".m3u" ) ) || LowerPath.EndsWith( wxT( ".m3u8" ) ) )
{
return ReadM3uStream( Ins );
}
else if( LowerPath.EndsWith( wxT( ".xspf" ) ) )
{
return ReadXspfStream( Ins );
}
else if( LowerPath.EndsWith( wxT( ".asx" ) ) )
{
return ReadAsxStream( Ins );
}
}
else
{
guLogError( wxT( "Could not get the playlist '%s'" ), uri.c_str() );
}
}
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::Save( const wxString &filename, const bool relative )
{
if( filename.Lower().EndsWith( wxT( ".pls" ) ) )
{
return WritePlsFile( filename, relative );
}
else if( filename.Lower().EndsWith( wxT( ".xspf" ) ) )
{
return WriteXspfFile( filename, relative );
}
else if( filename.Lower().EndsWith( wxT( ".asx" ) ) )
{
return WriteAsxFile( filename, relative );
}
else
{
wxString FileName = filename;
if( !FileName.Lower().EndsWith( wxT( ".m3u" ) ) )
FileName += wxT( ".m3u" );
return WriteM3uFile( FileName, relative );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadPlsStream( wxInputStream &playlist, const wxString &path )
{
wxFileConfig * PlayList = new wxFileConfig( playlist );
if( PlayList )
{
if( PlayList->HasGroup( wxT( "playlist" ) ) )
{
PlayList->SetPath( wxT( "playlist" ) );
int Count;
if( PlayList->Read( wxT( "numberofentries" ), &Count ) )
{
guLogMessage( wxT( "Found a playlist with %i items" ), Count );
if( !Count )
{
guLogMessage( wxT( "This station playlist is empty" ) );
}
else
{
for( int Index = 1; Index <= Count; Index++ )
{
wxString Location;
wxString Title;
if( PlayList->Read( wxString::Format( wxT( "File%u" ), Index ), &Location ) &&
!Location.IsEmpty() )
{
PlayList->Read( wxString::Format( wxT( "Title%u" ), Index ), &Title );
wxURI Uri( Location );
if( Location.StartsWith( wxT( "/" ) ) || Uri.HasScheme() || path.IsEmpty() )
{
m_Playlist.Add( new guPlaylistItem( Location, Title ) );
}
else
{
wxFileName FileName( Location );
FileName.Normalize( wxPATH_NORM_ALL, path );
m_Playlist.Add( new guPlaylistItem( FileName.GetFullPath(), Title ) );
}
}
}
return true;
}
}
}
else
{
guLogError( wxT( "ee: Station Playlist without 'playlist' group" ) );
}
delete PlayList;
}
else
{
guLogError( wxT( "Could not read the playlist stream" ) );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadPlsFile( const wxString &filename )
{
guLogMessage( wxT( "ReadPlsFile( '%s' )" ), filename.c_str() );
wxFileInputStream Ins( filename );
if( Ins.IsOk() )
{
return ReadPlsStream( Ins, wxPathOnly( filename ) );
}
else
{
guLogError( wxT( "Could not open the playlist file '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadM3uStream( wxInputStream &playlist, const wxString &path )
{
wxString M3uFile;
wxStringOutputStream Outs( &M3uFile );
playlist.Read( Outs );
if( !M3uFile.IsEmpty() )
{
//guLogMessage( wxT( "Content...\n%s" ), M3uFile.c_str() );
wxString ItemName;
wxArrayString Lines = wxStringTokenize( M3uFile, wxT( "\n" ) );
int Count = Lines.Count();
for( int Index = 0; Index < Count; Index++ )
{
Lines[ Index ].Trim( false ).Trim( true );
if( Lines[ Index ].IsEmpty() || ( Lines[ Index ].Find( wxT( "#EXTM3U" ) ) != wxNOT_FOUND ) )
{
continue;
}
else if( Lines[ Index ].Find( wxT( "#EXTINF" ) ) != wxNOT_FOUND )
{
if( Lines[ Index ].Find( wxT( "," ) ) != wxNOT_FOUND )
ItemName = Lines[ Index ].AfterLast( wxT( ',' ) );
}
else
{
wxURI Uri( Lines[ Index ] );
if( Lines[ Index ].StartsWith( wxT( "/" ) ) || Uri.HasScheme() || path.IsEmpty() )
{
m_Playlist.Add( new guPlaylistItem( Lines[ Index ], ItemName ) );
}
else
{
wxFileName FileName( Lines[ Index ] );
FileName.Normalize( wxPATH_NORM_ALL, path );
m_Playlist.Add( new guPlaylistItem( FileName.GetFullPath(), ItemName ) );
}
//guLogMessage( wxT( "%s - %s -> %s" ), path.c_str(), Lines[ Index ].c_str(), ( FileName.GetPathWithSep() + FileName.GetFullName() ).c_str() );
ItemName = wxEmptyString;
}
}
return true;
}
else
{
guLogError( wxT( "Empty playlist file stream" ) );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadM3uFile( const wxString &filename )
{
wxFileInputStream Ins( filename );
if( Ins.IsOk() )
{
return ReadM3uStream( Ins, wxPathOnly( filename ) );
}
else
{
guLogError( wxT( "Could not open the playlist file '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
void guPlaylistFile::ReadXspfTrack( wxXmlNode * XmlNode )
{
wxString Title;
wxString Location;
while( XmlNode )
{
if( XmlNode->GetName().Lower() == wxT( "title" ) )
{
Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName().Lower() == wxT( "location" ) )
{
Location = XmlNode->GetNodeContent();
}
XmlNode = XmlNode->GetNext();
}
if( !Location.IsEmpty() )
m_Playlist.Add( new guPlaylistItem( Location, Title ) );
}
// -------------------------------------------------------------------------------- //
void guPlaylistFile::ReadXspfTrackList( wxXmlNode * XmlNode )
{
while( XmlNode )
{
if( XmlNode->GetName().Lower() == wxT( "track" ) )
{
ReadXspfTrack( XmlNode->GetChildren() );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
void guPlaylistFile::ReadXspfPlayList( wxXmlNode * XmlNode )
{
while( XmlNode )
{
if( XmlNode->GetName().Lower() == wxT( "title" ) )
{
m_Name = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName().Lower() == wxT( "tracklist" ) )
{
ReadXspfTrackList( XmlNode->GetChildren() );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadXspfStream( wxInputStream &playlist )
{
wxXmlDocument XmlDoc( playlist );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName().Lower() == wxT( "playlist" ) )
{
ReadXspfPlayList( XmlNode->GetChildren() );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadXspfFile( const wxString &filename )
{
wxFileInputStream Ins( filename );
if( Ins.IsOk() )
{
return ReadXspfStream( Ins );
}
else
{
guLogError( wxT( "Could not open the playlist file '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
void guPlaylistFile::ReadAsxEntry( wxXmlNode * XmlNode )
{
wxString Title;
wxString Location;
while( XmlNode )
{
if( XmlNode->GetName().Lower() == wxT( "title" ) )
{
Title = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName().Lower() == wxT( "ref" ) )
{
XmlNode->GetAttribute( wxT( "href" ), &Location );
}
XmlNode = XmlNode->GetNext();
}
if( !Location.IsEmpty() )
m_Playlist.Add( new guPlaylistItem( Location, Title ) );
}
// -------------------------------------------------------------------------------- //
void guPlaylistFile::ReadAsxPlayList( wxXmlNode * XmlNode )
{
while( XmlNode )
{
if( XmlNode->GetName().Lower() == wxT( "title" ) )
{
m_Name = XmlNode->GetNodeContent();
}
else if( XmlNode->GetName().Lower() == wxT( "entry" ) )
{
ReadAsxEntry( XmlNode->GetChildren() );
}
XmlNode = XmlNode->GetNext();
}
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadAsxStream( wxInputStream &playlist )
{
wxXmlDocument XmlDoc( playlist );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName().Lower() == wxT( "asx" ) )
{
ReadAsxPlayList( XmlNode->GetChildren() );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::ReadAsxFile( const wxString &filename )
{
wxFileInputStream Ins( filename );
if( Ins.IsOk() )
{
return ReadAsxStream( Ins );
}
else
{
guLogError( wxT( "Could not open the playlist file '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::WritePlsFile( const wxString &filename, const bool relative )
{
wxFile PlsFile;
if( PlsFile.Create( filename, true ) && PlsFile.IsOpened() )
{
PlsFile.Write( wxT( "[playlist]\n" ) );
int Count = m_Playlist.Count();
PlsFile.Write( wxString::Format( wxT( "numberofentries=%u\n" ), Count ) );
for( int Index = 0; Index < Count; Index++ )
{
PlsFile.Write( wxString::Format( wxT( "File%u=%s\n" ), Index + 1,
m_Playlist[ Index ].GetLocation( relative, wxPathOnly( filename ) ).c_str() ) );
PlsFile.Write( wxString::Format( wxT( "Title%u=%s\n" ), Index + 1,
m_Playlist[ Index ].m_Name.c_str() ) );
}
PlsFile.Close();
}
else
{
guLogError( wxT( "Could not open the plsfile '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::WriteM3uFile( const wxString &filename, const bool relative )
{
wxFile M3uFile;
if( M3uFile.Create( filename, true ) && M3uFile.IsOpened() )
{
M3uFile.Write( wxT( "#EXTM3U\n" ) );
int Count = m_Playlist.Count();
for( int Index = 0; Index < Count; Index++ )
{
M3uFile.Write( wxString::Format( wxT( "#EXTINF:%i,%s\n" ), m_Playlist[ Index ].m_Length, m_Playlist[ Index ].m_Name.c_str() ) );
M3uFile.Write( m_Playlist[ Index ].GetLocation( relative, wxPathOnly( filename ) ) );
M3uFile.Write( wxT( "\n" ) );
}
M3uFile.Close();
}
else
{
guLogError( wxT( "Could not open the m3ufile '%s'" ), filename.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::WriteXspfFile( const wxString &filename, const bool relative )
{
wxXmlDocument OutXml;
//OutXml.SetRoot( );
wxXmlNode * RootNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "playlist" ) );
wxXmlNode * TitleNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "title" ) );
wxXmlNode * TitleNodeVal = new wxXmlNode( wxXML_TEXT_NODE, wxT( "title" ), m_Name );
TitleNode->AddChild( TitleNodeVal );
RootNode->AddChild( TitleNode );
wxXmlNode * TrackListNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "trackList" ) );
int Count = m_Playlist.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxXmlNode * TrackNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "track" ) );
wxXmlNode * LocationNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "location" ) );
wxXmlNode * LocationNodeVal = new wxXmlNode( wxXML_TEXT_NODE, wxT( "location" ), m_Playlist[ Index ].GetLocation( relative, wxPathOnly( filename ) ) );
LocationNode->AddChild( LocationNodeVal );
wxXmlNode * TitleNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "title" ) );
wxXmlNode * TitleNodeVal = new wxXmlNode( wxXML_TEXT_NODE, wxT( "title" ), m_Playlist[ Index ].m_Name );
TitleNode->AddChild( TitleNodeVal );
TrackNode->AddChild( LocationNode );
TrackNode->AddChild( TitleNode );
TrackListNode->AddChild( TrackNode );
}
RootNode->AddChild( TrackListNode );
OutXml.SetRoot( RootNode );
return OutXml.Save( filename );
}
// -------------------------------------------------------------------------------- //
bool guPlaylistFile::WriteAsxFile( const wxString &filename, const bool relative )
{
wxXmlDocument OutXml;
//OutXml.SetRoot( );
wxXmlNode * RootNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "asx" ) );
wxXmlNode * TitleNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "title" ) );
wxXmlNode * TitleNodeVal = new wxXmlNode( wxXML_TEXT_NODE, wxT( "title" ), m_Name );
TitleNode->AddChild( TitleNodeVal );
RootNode->AddChild( TitleNode );
int Count = m_Playlist.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxXmlNode * EntryNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "entry" ) );
wxXmlNode * RefNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "ref" ) );
wxXmlAttribute * RefNodeVal = new wxXmlAttribute( wxT( "href" ), m_Playlist[ Index ].GetLocation( relative, wxPathOnly( filename ) ), NULL );
RefNode->SetAttributes( RefNodeVal );
wxXmlNode * TitleNode = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "title" ) );
wxXmlNode * TitleNodeVal = new wxXmlNode( wxXML_TEXT_NODE, wxT( "title" ), m_Playlist[ Index ].m_Name );
TitleNode->AddChild( TitleNodeVal );
EntryNode->AddChild( RefNode );
EntryNode->AddChild( TitleNode );
RootNode->AddChild( EntryNode );
}
OutXml.SetRoot( RootNode );
return OutXml.Save( filename );
}
// -------------------------------------------------------------------------------- //
// guCuePlaylistFile
// -------------------------------------------------------------------------------- //
guCuePlaylistFile::guCuePlaylistFile( const wxString &location )
{
m_Location = location;
m_TrackLength = 0;
Load( location );
}
// -------------------------------------------------------------------------------- //
unsigned int RedBookToMTime( const wxString &rbtime )
{
guLogMessage( wxT( "RedBookToMTime( '%s' )" ), rbtime.c_str() );
// 01:23:45
wxArrayString Sections = wxStringTokenize( rbtime, wxT( ":" ) );
if( Sections.Count() != 3 )
return 0;
unsigned long Mins;
unsigned long Secs;
unsigned long Frames;
Sections[ 0 ].ToULong( &Mins );
Sections[ 1 ].ToULong( &Secs );
Sections[ 2 ].ToULong( &Frames );
return ( Mins * 60 * 1000 ) +
( Secs * 1000 ) +
( Frames * 1000 / 75 );
}
// -------------------------------------------------------------------------------- //
inline wxString RemoveQuotationMark( const wxString &text )
{
//guLogMessage( wxT( "RemoveQuotationMark: '%s'" ), text.c_str() );
if( text.StartsWith( wxT( "\"" ) ) )
{
return text.Mid( 1, text.Length() - 2 );
}
return text;
}
// -------------------------------------------------------------------------------- //
inline wxString GetKeyValue( const wxString &line, const wxString &key )
{
//guLogMessage( wxT( "GetKeyValue: '%s' ==> '%s'" ), line.c_str(), key.c_str() );
int Pos = line.Find( key );
if( Pos != wxNOT_FOUND )
{
return line.Mid( Pos + key.Length() ).Strip( wxString::both );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
bool guCuePlaylistFile::LoadFromText( const wxString &content )
{
if( !content.IsEmpty() )
{
wxArrayString Lines = wxStringTokenize( content, wxT( "\n" ) );
int CurrentTrack = wxNOT_FOUND;
int Count = Lines.Count();
for( int Index = 0; Index < Count; Index++ )
{
Lines[ Index ].Trim( false ).Trim( true );
wxString Line = Lines[ Index ];
//guLogMessage( wxT( "'%s'" ), Line.c_str() );
wxArrayString Keys = wxStringTokenize( Line, wxT( " " ) );
if( !Keys.Count() )
continue;
if( Keys[ 0 ] == wxT( "FILE" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_TrackPath = RemoveQuotationMark( GetKeyValue( Line, wxT( "FILE" ) ).BeforeLast( wxT( ' ' ) ) );
if( !m_TrackPath.StartsWith( wxT( "/" ) ) )
m_TrackPath = wxPathOnly( m_Location ) + wxT( "/" ) + m_TrackPath;
guTagInfo * TagInfo = guGetTagInfoHandler( m_TrackPath );
if( TagInfo )
{
if( TagInfo->Read() )
{
m_TrackLength = TagInfo->m_Length;
}
delete TagInfo;
}
}
else
{
m_PlaylistItems[ CurrentTrack ].m_TrackPath =
RemoveQuotationMark( GetKeyValue( Line, wxT( "FILE" ) ).BeforeLast( wxT( ' ' ) ) );
if( !m_PlaylistItems[ CurrentTrack ].m_TrackPath.StartsWith( wxT( "/" ) ) )
m_TrackPath = wxPathOnly( m_Location ) + wxT( "/" ) + m_PlaylistItems[ CurrentTrack ].m_TrackPath;
}
}
else if( Keys[ 0 ] == wxT( "INDEX" ) )
{
if( Keys[ 1 ] == wxT( "01" ) )
{
m_PlaylistItems[ CurrentTrack ].m_Start = RedBookToMTime( GetKeyValue( Line, wxT( "01" ) ) );
if( !m_PlaylistItems[ CurrentTrack ].m_Start ) // the first track starts at 1ms to make m_Offset = 1
m_PlaylistItems[ CurrentTrack ].m_Start++;
if( CurrentTrack > 0 )
{
m_PlaylistItems[ CurrentTrack - 1 ].m_Length = m_PlaylistItems[ CurrentTrack ].m_Start -
m_PlaylistItems[ CurrentTrack - 1 ].m_Start;
// Set the length of the last track
if( Index == ( Count - 1 ) )
{
m_PlaylistItems[ CurrentTrack ].m_Length = m_TrackLength - m_PlaylistItems[ CurrentTrack ].m_Start;
}
}
}
}
else if( Keys[ 0 ] == wxT( "PERFORMER" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_ArtistName = RemoveQuotationMark( GetKeyValue( Line, wxT( "PERFORMER" ) ) );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_ArtistName = RemoveQuotationMark( GetKeyValue( Line, wxT( "PERFORMER" ) ) );
if( !m_ArtistName.IsEmpty() )
{
m_PlaylistItems[ CurrentTrack ].m_AlbumArtist = m_ArtistName;
}
}
}
else if( Keys[ 0 ] == wxT( "REM" ) )
{
if( Keys[ 1 ] == wxT( "GENRE" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_Genre = RemoveQuotationMark( GetKeyValue( Line, wxT( "GENRE" ) ) );
guLogMessage( wxT( "Genre : '%s'" ), m_Genre.c_str() );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_Genre = RemoveQuotationMark( GetKeyValue( Line, wxT( "GENRE" ) ) );
guLogMessage( wxT( "Genre %i: '%s'" ), CurrentTrack, m_Genre.c_str() );
}
}
else if( Keys[ 1 ] == wxT( "DATE" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_Year = RemoveQuotationMark( GetKeyValue( Line, wxT( "DATE" ) ) );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_Year = RemoveQuotationMark( GetKeyValue( Line, wxT( "DATE" ) ) );
}
}
else if( Keys[ 1 ] == wxT( "COMMENT" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_Comment = RemoveQuotationMark( GetKeyValue( Line, wxT( "COMMENT" ) ) );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_Comment = RemoveQuotationMark( GetKeyValue( Line, wxT( "COMMENT" ) ) );
}
}
}
else if( Keys[ 0 ] == wxT( "SONGWRITER" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_Composer = RemoveQuotationMark( GetKeyValue( Line, wxT( "SONGWRITER" ) ) );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_Composer = RemoveQuotationMark( GetKeyValue( Line, wxT( "SONGWRITER" ) ) );
}
}
else if( Keys[ 0 ] == wxT( "TITLE" ) )
{
if( CurrentTrack == wxNOT_FOUND )
{
m_AlbumName = RemoveQuotationMark( GetKeyValue( Line, wxT( "TITLE" ) ) );
}
else
{
m_PlaylistItems[ CurrentTrack ].m_Name = RemoveQuotationMark( GetKeyValue( Line, wxT( "TITLE" ) ) );
}
}
else if( Keys[ 0 ] == wxT( "TRACK" ) )
{
m_PlaylistItems.Add( new guCuePlaylistItem() );
CurrentTrack++;
guCuePlaylistItem &PlaylistItem = m_PlaylistItems[ CurrentTrack ];
PlaylistItem.m_Genre = m_Genre;
PlaylistItem.m_AlbumName = m_AlbumName;
PlaylistItem.m_Comment = m_Comment;
PlaylistItem.m_ArtistName = m_ArtistName;
PlaylistItem.m_Year = m_Year;
PlaylistItem.m_TrackPath = m_TrackPath;
}
}
}
else
{
guLogError( wxT( "Empty playlist '%s'" ), m_Location.c_str() );
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guCuePlaylistFile::Load( const wxString &location )
{
wxString Content;
m_Location = location;
if( !location.IsEmpty() )
{
wxURI Uri( location );
if( location.StartsWith( wxT( "file://" ) ) )
{
m_Location = wxURI::Unescape( Uri.GetPath() );
}
else
{
m_Location = location;
}
if( Uri.IsReference() )
{
//guLogMessage( wxT( "CuePlaylist from file : '%s'" ), m_Location.c_str() );
wxFile PlaylistFile( m_Location, wxFile::read );
if( !PlaylistFile.IsOpened() )
{
guLogMessage( wxT( "Could not open '%s'" ), m_Location.c_str() );
return false;
}
int DataSize = PlaylistFile.Length();
if( !DataSize )
{
guLogMessage( wxT( "Playlist '%s' with 0 length" ), m_Location.c_str() );
return false;
}
char * Buffer = ( char * ) malloc( DataSize + 1 );
if( Buffer )
{
if( PlaylistFile.Read( Buffer, DataSize ) == DataSize )
{
Content = wxString( Buffer, wxConvAuto() );
if( Content.IsEmpty() )
{
Content = wxString( Buffer, wxConvUTF8 );
if( Content.IsEmpty() )
{
Content = wxString( Buffer, wxConvISO8859_1 );
if( Content.IsEmpty() )
{
for( int Index = 0; Index < DataSize; Index++ )
{
Content += Buffer[ Index ];
}
}
}
}
}
else
{
guLogMessage( wxT( "Could not read '%s' %u bytes" ), location.c_str(), DataSize );
}
free( Buffer );
}
guLogMessage( wxT( "Content:\n%s" ), Content.c_str() );
}
else
{
Content = GetUrlContent( location );
}
return LoadFromText( Content );
}
return false;
}
}
// -------------------------------------------------------------------------------- //
| 31,595
|
C++
|
.cpp
| 826
| 28.117433
| 159
| 0.465018
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,612
|
ImportFiles.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/importfiles/ImportFiles.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ImportFiles.h"
#include "Config.h"
#include "Images.h"
#include "MediaViewer.h"
#include "TagInfo.h"
#include "GstTypeFinder.h"
#include <wx/filedlg.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guImportFiles::guImportFiles( wxWindow * parent, guMediaViewer * mediaviewer, guTrackArray * tracks )
// wxDialog( parent, wxID_ANY, _( "Import Files" ), wxDefaultPosition, wxSize( 480,340 ), wxDEFAULT_DIALOG_STYLE )
{
m_MediaViewer = mediaviewer;
m_Tracks = tracks;
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
wxPoint WindowPos;
WindowPos.x = Config->ReadNum( CONFIG_KEY_IMPORT_FILES_POS_X, -1, CONFIG_PATH_IMPORT_FILES_POSITION );
WindowPos.y = Config->ReadNum( CONFIG_KEY_IMPORT_FILES_POS_Y, -1, CONFIG_PATH_IMPORT_FILES_POSITION );
wxSize WindowSize;
WindowSize.x = Config->ReadNum( CONFIG_KEY_IMPORT_FILES_WIDTH, 480, CONFIG_PATH_IMPORT_FILES_POSITION );
WindowSize.y = Config->ReadNum( CONFIG_KEY_IMPORT_FILES_HEIGHT, 340, CONFIG_PATH_IMPORT_FILES_POSITION );
Create( parent, wxID_ANY, _( "Import Files" ), WindowPos, WindowSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX );
CreateControls();
}
// -------------------------------------------------------------------------------- //
guImportFiles::~guImportFiles()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
wxPoint WindowPos = GetPosition();
Config->WriteNum( CONFIG_KEY_IMPORT_FILES_POS_X, WindowPos.x, CONFIG_PATH_IMPORT_FILES_POSITION );
Config->WriteNum( CONFIG_KEY_IMPORT_FILES_POS_Y, WindowPos.y, CONFIG_PATH_IMPORT_FILES_POSITION );
wxSize WindowSize = GetSize();
Config->WriteNum( CONFIG_KEY_IMPORT_FILES_WIDTH, WindowSize.x, CONFIG_PATH_IMPORT_FILES_POSITION );
Config->WriteNum( CONFIG_KEY_IMPORT_FILES_HEIGHT, WindowSize.y, CONFIG_PATH_IMPORT_FILES_POSITION );
m_CopyToSetupBtn->Unbind( wxEVT_BUTTON, &guImportFiles::OnCopyToSetupClicked, this );
m_FilesListBox->Unbind( wxEVT_LISTBOX, &guImportFiles::OnFileSelected, this );
m_AddFilesBtn->Unbind( wxEVT_BUTTON, &guImportFiles::OnAddFilesClicked, this );
m_DelFilesBtn->Unbind( wxEVT_BUTTON, &guImportFiles::OnDelFilesClicked, this );
Unbind( guConfigUpdatedEvent, &guImportFiles::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guImportFiles::CreateControls( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer * MainStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxFlexGridSizer * CopyToSizer = new wxFlexGridSizer( 2, 0, 0 );
CopyToSizer->AddGrowableCol( 1 );
CopyToSizer->SetFlexibleDirection( wxBOTH );
CopyToSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxStaticText * CopyToStaticText = new wxStaticText( this, wxID_ANY, _( "Copy to Option:" ), wxDefaultPosition, wxDefaultSize, 0 );
CopyToStaticText->Wrap( -1 );
CopyToSizer->Add( CopyToStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 );
wxBoxSizer * CopyToChoiceSIzer = new wxBoxSizer( wxHORIZONTAL );
wxArrayString CopyToOptions = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
int Count = CopyToOptions.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
CopyToOptions[ Index ] = CopyToOptions[ Index ].BeforeFirst( wxT( ':' ) );
}
}
guMediaCollection * MediaCollection = m_MediaViewer->GetMediaCollection();
int CopyToIndex = CopyToOptions.Index( MediaCollection->m_DefaultCopyAction );
m_CopyToChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, CopyToOptions, 0 );
m_CopyToChoice->SetSelection( CopyToIndex );
CopyToChoiceSIzer->Add( m_CopyToChoice, 1, wxTOP|wxBOTTOM|wxEXPAND, 5 );
m_CopyToSetupBtn = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_search_engine ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
CopyToChoiceSIzer->Add( m_CopyToSetupBtn, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );
CopyToSizer->Add( CopyToChoiceSIzer, 1, wxEXPAND, 5 );
wxStaticText * DestPathStaticText = new wxStaticText( this, wxID_ANY, _( "Destination Folder:" ), wxDefaultPosition, wxDefaultSize, 0 );
DestPathStaticText->Wrap( -1 );
CopyToSizer->Add( DestPathStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
m_DestPathDirPicker = new wxDirPickerCtrl( this, wxID_ANY, wxEmptyString, _( "Select a folder" ), wxDefaultPosition, wxDefaultSize, wxDIRP_DEFAULT_STYLE|wxDIRP_DIR_MUST_EXIST );
m_DestPathDirPicker->SetPath( m_MediaViewer->AudioPath() );
CopyToSizer->Add( m_DestPathDirPicker, 0, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
MainStaticBoxSizer->Add( CopyToSizer, 0, wxEXPAND, 5 );
wxStaticBoxSizer * FilesSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _( " Files " ) ), wxVERTICAL );
m_FilesListBox = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_MULTIPLE );
Count = m_Tracks->Count();
for( int Index = 0; Index < Count; Index++ )
{
const guTrack & CurTrack = m_Tracks->Item( Index );
wxString CurFile = CurTrack.m_FileName.AfterLast( wxT( '/' ) );
if( CurTrack.m_Offset )
{
CurFile += wxT( "@" ) + LenToString( CurTrack.m_Offset );
CurFile += wxT( " / " ) + LenToString( CurTrack.m_Length );
}
m_FilesListBox->Append( CurFile );
}
FilesSizer->Add( m_FilesListBox, 1, wxEXPAND|wxALL, 5 );
wxBoxSizer * AddFilesSizer = new wxBoxSizer( wxHORIZONTAL );
m_AddFilesBtn = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_add ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
AddFilesSizer->Add( m_AddFilesBtn, 0, wxLEFT, 5 );
m_DelFilesBtn = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_del ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DelFilesBtn->Enable( false );
AddFilesSizer->Add( m_DelFilesBtn, 0, wxRIGHT, 5 );
AddFilesSizer->Add( 0, 0, 1, wxEXPAND, 5 );
m_FilesLabel = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_FilesLabel->Wrap( -1 );
AddFilesSizer->Add( m_FilesLabel, 0, wxRIGHT|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 );
FilesSizer->Add( AddFilesSizer, 0, wxEXPAND, 5 );
MainStaticBoxSizer->Add( FilesSizer, 1, wxEXPAND, 5 );
MainSizer->Add( MainStaticBoxSizer, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );
wxStdDialogButtonSizer * DlgButtons = new wxStdDialogButtonSizer();
m_DlgButtonsOK = new wxButton( this, wxID_OK );
m_DlgButtonsOK->Enable( !m_CopyToChoice->GetStringSelection().IsEmpty() && !m_DestPathDirPicker->GetPath().IsEmpty() && !m_FilesListBox->IsEmpty() );
DlgButtons->AddButton( m_DlgButtonsOK );
wxButton * DlgButtonsCancel = new wxButton( this, wxID_CANCEL );
DlgButtons->AddButton( DlgButtonsCancel );
DlgButtons->SetAffirmativeButton( m_DlgButtonsOK );
DlgButtons->SetCancelButton( DlgButtonsCancel );
DlgButtons->Realize();
MainSizer->Add( DlgButtons, 0, wxEXPAND|wxALL, 5 );
SetSizer( MainSizer );
Layout();
m_DlgButtonsOK->SetDefault();
UpdateCounters();
m_CopyToSetupBtn->Bind( wxEVT_BUTTON, &guImportFiles::OnCopyToSetupClicked, this );
m_FilesListBox->Bind( wxEVT_LISTBOX, &guImportFiles::OnFileSelected, this );
m_AddFilesBtn->Bind( wxEVT_BUTTON, &guImportFiles::OnAddFilesClicked, this );
m_DelFilesBtn->Bind( wxEVT_BUTTON, &guImportFiles::OnDelFilesClicked, this );
Bind( guConfigUpdatedEvent, &guImportFiles::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guImportFiles::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_COPYTO )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString CopyToOptions = Config->ReadAStr( CONFIG_KEY_COPYTO_OPTION, wxEmptyString, CONFIG_PATH_COPYTO );
int Count = CopyToOptions.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
CopyToOptions[ Index ] = CopyToOptions[ Index ].BeforeFirst( wxT( ':' ) );
}
}
wxString CurSelected = m_CopyToChoice->GetStringSelection();
m_CopyToChoice->Clear();
m_CopyToChoice->Append( CopyToOptions );
m_CopyToChoice->SetStringSelection( CurSelected );
}
}
// -------------------------------------------------------------------------------- //
void guImportFiles::OnCopyToSetupClicked( wxCommandEvent &event )
{
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_COPYTO );
wxPostEvent( ( wxEvtHandler * ) m_MediaViewer->GetMainFrame(), CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guImportFiles::OnFileSelected( wxCommandEvent &event )
{
m_DelFilesBtn->Enable( event.GetInt() != wxNOT_FOUND );
}
// -------------------------------------------------------------------------------- //
void guImportFiles::OnAddFilesClicked( wxCommandEvent &event )
{
wxArrayString mf_exts = guGstTypeFinder::getGTF().GetExtensions();
wxString gst_ext_str = "";
for( size_t i = 0; i<mf_exts.Count(); ++i )
gst_ext_str = gst_ext_str + "*." + mf_exts[ i ] + ";";
if( gst_ext_str.Len() )
gst_ext_str.Truncate( gst_ext_str.Len() - 1 );
wxFileDialog * FileDialog = new wxFileDialog( this, _( "Select files" ), wxGetHomeDir(), wxEmptyString,
wxString( _( "Audio files" ) ) + "|*.mp3;*.ogg;*.oga;*.flac;*.mp4;*.m4a;*.m4b;*.m4p;*.aac;*.wma;*.asf;*.ape;*.wav;*.aif;*.wv;*.tta;*.mpc;" + gst_ext_str + "|" +
wxString( _( "mp3 files" ) ) + wxT( " (*.mp3)|*.mp3|" ) +
wxString( _( "ogg files" ) ) + wxT( " (*.ogg;*.oga)|*.ogg;*.oga|" ) +
wxString( _( "flac files" ) ) + wxT( " (*.flac)|*.flac|" ) +
wxString( _( "mp4 files" ) ) + wxT( " (*.mp4;*.m4a)|*.mp4;*.m4a;*.m4b;*.m4p;*.aac|" ) +
wxString( _( "wma files" ) ) + wxT( " (*.wma;*.asf)|*.wma;*.asf|" ) +
wxString( _( "ape files" ) ) + wxT( " (*.ape)|*.ape|" ) +
wxString( _( "waf files" ) ) + wxT( " (*.wav)|*.wav|" ) +
wxString( _( "aif files" ) ) + wxT( " (*.aif)|*.aif|" ) +
wxString( _( "wv files" ) ) + wxT( " (*.wv)|*.wv|" ) +
wxString( _( "tta files" ) ) + wxT( " (*.tta)|*.tta|" ) +
wxString( _( "mpc files" ) ) + wxT( " (*.mpc)|*.mpc|" ) +
wxString( _( "other files" ) ) + "|" + gst_ext_str,
wxFD_OPEN|wxFD_FILE_MUST_EXIST|wxFD_MULTIPLE|wxFD_PREVIEW );
if( FileDialog )
{
if( FileDialog->ShowModal() == wxID_OK )
{
wxArrayString NewFiles;
FileDialog->GetPaths( NewFiles );
int Count = NewFiles.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxString NewFile = NewFiles[ Index ];
//guLogMessage( wxT( "Openning file '%s'" ), NewFile.c_str() );
if( wxFileExists( NewFile ) && guIsValidAudioFile( NewFile.Lower() ) )
{
guTrack * Track = new guTrack();
if( Track->ReadFromFile( NewFile ) )
{
Track->m_Type = guTRACK_TYPE_NOTDB;
m_Tracks->Add( Track );
m_FilesListBox->Append( NewFile.AfterLast( wxT( '/' ) ) );
}
else
{
delete Track;
}
}
}
UpdateCounters();
CheckButtons();
}
FileDialog->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guImportFiles::OnDelFilesClicked( wxCommandEvent &event )
{
wxArrayInt Selected;
m_FilesListBox->GetSelections( Selected );
int Count = Selected.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_FilesListBox->Delete( Selected[ Index ] );
m_Tracks->RemoveAt( Selected[ Index ] );
}
UpdateCounters();
CheckButtons();
}
// -------------------------------------------------------------------------------- //
void guImportFiles::CheckButtons( void )
{
m_DlgButtonsOK->Enable( !m_CopyToChoice->GetStringSelection().IsEmpty() && !m_DestPathDirPicker->GetPath().IsEmpty() && !m_FilesListBox->IsEmpty() );
}
// -------------------------------------------------------------------------------- //
void guImportFiles::UpdateCounters( void )
{
wxLongLong Size = 0;
wxLongLong Length = 0;
int Count = m_Tracks->Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = m_Tracks->Item( Index );
Size += Track.m_FileSize;
Length += Track.m_Length;
}
wxString SelInfo = wxString::Format( wxT( "%u " ), Count );
SelInfo += Count == 1 ? _( "track" ) : _( "tracks" );
SelInfo += wxString::Format( wxT( ", %s, %s" ),
LenToString( Length.GetValue() ).c_str(),
SizeToString( Size.GetValue() ).c_str() );
m_FilesLabel->SetLabel( SelInfo );
Layout();
}
else
{
m_FilesLabel->SetLabel( _( "No files added" ) );
Layout();
}
}
}
// -------------------------------------------------------------------------------- //
| 14,965
|
C++
|
.cpp
| 289
| 45.688581
| 178
| 0.603776
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,613
|
iPodMedia.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/ipodmedia/iPodMedia.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "iPodMedia.h"
#include "CoverEdit.h"
#include "MainFrame.h"
#include "MD5.h"
#include "SelCoverFile.h"
#include "TagInfo.h"
#include "Transcode.h"
#include "ShowImage.h"
#include "Utils.h"
#include <wx/tokenzr.h>
#ifdef WITH_LIBGPOD_SUPPORT
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
void inline CheckUpdateField( gchar ** fieldptr, const wxString &newval )
{
if( wxString( * fieldptr, wxConvUTF8 ) != newval )
{
free( * fieldptr );
* fieldptr = strdup( newval.ToUTF8() );
}
}
// -------------------------------------------------------------------------------- //
// guIpodLibrary
// -------------------------------------------------------------------------------- //
guIpodLibrary::guIpodLibrary( const wxString &dbpath, guPortableMediaDevice * portablemediadevice, Itdb_iTunesDB * ipoddb )
: guPortableMediaLibrary( dbpath, portablemediadevice )
{
m_iPodDb = ipoddb;
}
// -------------------------------------------------------------------------------- //
guIpodLibrary::~guIpodLibrary()
{
if( m_iPodDb )
{
itdb_free( m_iPodDb );
}
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::GetAlbumId( const wxString &album, const wxString &artist, const wxString &albumartist, const wxString &disk )
{
//guLogMessage( wxT( "guIpodLibrary::GetAlbumId" ) );
wxString query;
wxSQLite3ResultSet dbRes;
int RetVal = 0;
query = wxString::Format( wxT( "SELECT song_albumid FROM songs WHERE song_album = '%s' " ), escape_query_str( album ).c_str() );
if( !albumartist.IsEmpty() )
{
query += wxString::Format( wxT( "AND song_albumartist = '%s' " ), escape_query_str( albumartist ).c_str() );
}
else
{
query += wxString::Format( wxT( "AND song_artist = '%s' " ), escape_query_str( artist ).c_str() );
}
if( !disk.IsEmpty() )
{
query += wxString::Format( wxT( "AND song_disk = '%s' " ), escape_query_str( disk ).c_str() );
}
query += wxT( "LIMIT 1;" );
dbRes = m_Db->ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 );
}
else
{
dbRes.Finalize();
query = wxT( "SELECT MAX(song_albumid) FROM songs;" );
dbRes = ExecuteQuery( query );
if( dbRes.NextRow() )
{
RetVal = dbRes.GetInt( 0 ) + 1;
}
else
{
RetVal = 1;
}
}
dbRes.Finalize();
return RetVal;
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::CreateStaticPlayList( const wxString &name, const wxArrayInt &trackids )
{
guLogMessage( wxT( "guIpodMediaLibPanel::CreateStaticPlayList( '%s' )" ), name.c_str() );
wxString PlayListName = name;
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
guLogMessage( wxT( "Playlist with same name exists so delete it" ) );
itdb_playlist_remove( OldPlayList );
}
Itdb_Playlist * iPodPlayList = itdb_playlist_new( name.mb_str( wxConvFile ), false );
if( iPodPlayList )
{
guLogMessage( wxT( "Created the playlist" ) );
itdb_playlist_add( m_iPodDb, iPodPlayList, wxNOT_FOUND );
guLogMessage( wxT( "Attached to the database" ) );
guTrackArray Tracks;
GetSongs( trackids, &Tracks );
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guLogMessage( wxT( "Searching for track %s" ), Tracks[ Index ].m_FileName.c_str() );
Itdb_Track * iPodTrack = iPodFindTrack( Tracks[ Index ].m_FileName );
if( iPodTrack )
{
guLogMessage( wxT( "Adding track %s" ), Tracks[ Index ].m_FileName.c_str() );
itdb_playlist_add_track( iPodPlayList, iPodTrack, wxNOT_FOUND );
}
}
guLogMessage( wxT( "Savint the database" ) );
iPodFlush();
}
else
{
guLogMessage( wxT( "Could not create the playlist " ) );
}
return guDbLibrary::CreateStaticPlayList( name, trackids );
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::UpdateStaticPlayList( const int plid, const wxArrayInt &trackids )
{
guLogMessage( wxT( "guIpodLibrary::UpdateStaticPlayList" ) );
wxString PlayListName = GetPlayListName( plid );
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
GList * Tracks = OldPlayList->members;
while( Tracks )
{
Itdb_Track * CurTrack = ( Itdb_Track * ) Tracks->data;
if( CurTrack )
itdb_playlist_remove_track( OldPlayList, CurTrack );
Tracks = Tracks->next;
}
guTrackArray PlayListTracks;
GetSongs( trackids, &PlayListTracks );
int Count = PlayListTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = iPodFindTrack( PlayListTracks[ Index ].m_FileName );
if( iPodTrack )
{
itdb_playlist_add_track( OldPlayList, iPodTrack, wxNOT_FOUND );
}
}
iPodFlush();
}
return guDbLibrary::UpdateStaticPlayList( plid, trackids );
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::AppendStaticPlayList( const int plid, const wxArrayInt &trackids )
{
guLogMessage( wxT( "guIpodLibrary::AppendStaticPlayList" ) );
wxString PlayListName = GetPlayListName( plid );
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
guTrackArray PlayListTracks;
GetSongs( trackids, &PlayListTracks );
int Count = PlayListTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = iPodFindTrack( PlayListTracks[ Index ].m_FileName );
if( iPodTrack )
{
itdb_playlist_add_track( OldPlayList, iPodTrack, wxNOT_FOUND );
}
}
iPodFlush();
}
return guDbLibrary::AppendStaticPlayList( plid, trackids );
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::DelPlaylistSetIds( const int plid, const wxArrayInt &trackids )
{
guLogMessage( wxT( "guIpodLibrary::DelPlaylistSetIds" ) );
wxString PlayListName = GetPlayListName( plid );
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
guTrackArray PlayListTracks;
GetSongs( trackids, &PlayListTracks );
int Count = PlayListTracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = iPodFindTrack( PlayListTracks[ Index ].m_FileName );
if( iPodTrack )
{
itdb_playlist_remove_track( OldPlayList, iPodTrack );
}
}
iPodFlush();
}
return guDbLibrary::DelPlaylistSetIds( plid, trackids );
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::SetPlayListName( const int plid, const wxString &newname )
{
guLogMessage( wxT( "guIpodLibrary::SetPlayListName" ) );
wxString PlayListName = GetPlayListName( plid );
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
CheckUpdateField( &OldPlayList->name, newname );
iPodFlush();
}
else
{
guLogMessage( wxT( "Could not find the playlist '%s'" ), PlayListName.c_str() );
}
guDbLibrary::SetPlayListName( plid, newname );
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::DeletePlayList( const int plid )
{
guLogMessage( wxT( "guIpodLibrary::DeletePlayList" ) );
wxString PlayListName = GetPlayListName( plid );
Itdb_Playlist * OldPlayList = itdb_playlist_by_name( m_iPodDb, PlayListName.char_str( wxConvUTF8 ) );
if( OldPlayList )
{
itdb_playlist_remove( OldPlayList );
iPodFlush();
}
guDbLibrary::DeletePlayList( plid );
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::UpdateStaticPlayListFile( const int plid )
{
}
// -------------------------------------------------------------------------------- //
Itdb_Playlist * guIpodLibrary::CreateiPodPlayList( const wxString &path, const wxArrayString &filenames )
{
guLogMessage( wxT( "guIpodLibrary::CreateiPodPlayList( '%s' )" ), wxFileNameFromPath( path ).BeforeLast( wxT( '.' ) ).c_str() );
Itdb_Playlist * iPodPlayList = itdb_playlist_new( wxFileNameFromPath( path ).BeforeLast( wxT( '.' ) ).mb_str( wxConvFile ), false );
if( iPodPlayList )
{
itdb_playlist_add( m_iPodDb, iPodPlayList, wxNOT_FOUND );
int Count = filenames.Count();
for( int Index = 0; Index < Count; Index++ )
{
guLogMessage( wxT( "Trying to search for: '%s'" ), filenames[ Index ].c_str() );
Itdb_Track * iPodTrack = iPodFindTrack( filenames[ Index ] );
if( iPodTrack )
{
guLogMessage( wxT( "Found the track" ) );
itdb_playlist_add_track( iPodPlayList, iPodTrack, wxNOT_FOUND );
}
}
guLogMessage( wxT( "Playlist: '%s' with %i tracks" ), wxString( iPodPlayList->name, wxConvUTF8 ).c_str(), iPodPlayList->num );
iPodFlush();
}
else
{
guLogMessage( wxT( "Could not create the playlist " ) );
}
return iPodPlayList;
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::CreateDynamicPlayList( const wxString &name, const guDynPlayList * playlist )
{
guLogMessage( wxT( "CreateDynamicPlaylist..." ) );
Itdb_Playlist * DynPlayList = itdb_playlist_new( name.mb_str( wxConvFile ), true );
if( DynPlayList )
{
itdb_playlist_add( m_iPodDb, DynPlayList, wxNOT_FOUND );
if( !playlist->m_Sorted )
{
DynPlayList->sortorder = ITDB_PSO_MANUAL;
}
else
{
switch( playlist->m_SortType )
{
case guDYNAMIC_FILTER_ORDER_TITLE :
DynPlayList->sortorder = ITDB_PSO_TITLE;
break;
case guDYNAMIC_FILTER_ORDER_ARTIST :
DynPlayList->sortorder = ITDB_PSO_ARTIST;
break;
case guDYNAMIC_FILTER_ORDER_ALBUMARTIST :
DynPlayList->sortorder = ITDB_PSO_MANUAL;
break;
case guDYNAMIC_FILTER_ORDER_ALBUM :
DynPlayList->sortorder = ITDB_PSO_ALBUM;
break;
case guDYNAMIC_FILTER_ORDER_GENRE :
DynPlayList->sortorder = ITDB_PSO_GENRE;
break;
case guDYNAMIC_FILTER_ORDER_LABEL :
DynPlayList->sortorder = ITDB_PSO_GROUPING;
break;
case guDYNAMIC_FILTER_ORDER_COMPOSER :
DynPlayList->sortorder = ITDB_PSO_COMPOSER;
break;
case guDYNAMIC_FILTER_ORDER_YEAR :
DynPlayList->sortorder = ITDB_PSO_YEAR;
break;
case guDYNAMIC_FILTER_ORDER_RATING :
DynPlayList->sortorder = ITDB_PSO_RATING;
break;
case guDYNAMIC_FILTER_ORDER_LENGTH :
DynPlayList->sortorder = ITDB_PSO_TIME;
break;
case guDYNAMIC_FILTER_ORDER_PLAYCOUNT :
DynPlayList->sortorder = ITDB_PSO_PLAYCOUNT;
break;
case guDYNAMIC_FILTER_ORDER_LASTPLAY :
DynPlayList->sortorder = ITDB_PSO_TIME_PLAYED;
break;
case guDYNAMIC_FILTER_ORDER_ADDEDDATE :
DynPlayList->sortorder = ITDB_PSO_TIME_ADDED;
break;
case guDYNAMIC_FILTER_ORDER_RANDOM :
DynPlayList->sortorder = ITDB_PSO_MANUAL;
break;
}
}
Itdb_SPLPref * PlaylistPref = &DynPlayList->splpref;
PlaylistPref->liveupdate = true;
PlaylistPref->checkrules = playlist->m_Filters.Count();
PlaylistPref->checklimits = playlist->m_Limited;
if( playlist->m_Limited )
{
PlaylistPref->limitvalue = playlist->m_LimitValue;
switch( playlist->m_LimitType )
{
case guDYNAMIC_FILTER_LIMIT_TRACKS :
PlaylistPref->limittype = ITDB_LIMITTYPE_SONGS;
break;
case guDYNAMIC_FILTER_LIMIT_MINUTES :
PlaylistPref->limittype = ITDB_LIMITTYPE_MINUTES;
break;
case guDYNAMIC_FILTER_LIMIT_MEGABYTES :
PlaylistPref->limittype = ITDB_LIMITTYPE_MB;
break;
case guDYNAMIC_FILTER_LIMIT_GIGABYTES :
PlaylistPref->limittype = ITDB_LIMITTYPE_GB;
break;
}
}
Itdb_SPLRules * PlaylistRules = &DynPlayList->splrules;
PlaylistRules->match_operator = playlist->m_AnyOption ? ITDB_SPLMATCH_OR : ITDB_SPLMATCH_AND;
guLogMessage( wxT( "*** Creating new Playlist : '%s'" ), name.c_str() );
guLogMessage( wxT( "liveupdate : %i" ), PlaylistPref->liveupdate );
guLogMessage( wxT( "checkrules : %i" ), PlaylistPref->checkrules );
guLogMessage( wxT( "checklimits : %i" ), PlaylistPref->checklimits );
guLogMessage( wxT( "limittype : %i" ), PlaylistPref->limittype );
int Count = playlist->m_Filters.Count();
for( int Index = 0; Index < Count; Index++ )
{
Itdb_SPLRule * PlaylistRule;
if( Index > 0 )
PlaylistRule = itdb_splr_add_new( DynPlayList, wxNOT_FOUND );
else
PlaylistRule = ( Itdb_SPLRule * ) PlaylistRules->rules->data;
if( PlaylistRule )
{
guFilterItem * FilterItem = &playlist->m_Filters[ Index ];
switch( FilterItem->m_Type )
{
case guDYNAMIC_FILTER_TYPE_TITLE :
PlaylistRule->field = ITDB_SPLFIELD_SONG_NAME;
break;
case guDYNAMIC_FILTER_TYPE_ARTIST :
PlaylistRule->field = ITDB_SPLFIELD_ARTIST;
break;
case guDYNAMIC_FILTER_TYPE_ALBUMARTIST :
PlaylistRule->field = ITDB_SPLFIELD_ALBUMARTIST;
break;
case guDYNAMIC_FILTER_TYPE_ALBUM :
PlaylistRule->field = ITDB_SPLFIELD_ALBUM;
break;
case guDYNAMIC_FILTER_TYPE_GENRE :
PlaylistRule->field = ITDB_SPLFIELD_GENRE;
break;
case guDYNAMIC_FILTER_TYPE_LABEL :
PlaylistRule->field = ITDB_SPLFIELD_GROUPING;
break;
case guDYNAMIC_FILTER_TYPE_COMPOSER :
PlaylistRule->field = ITDB_SPLFIELD_COMPOSER;
break;
case guDYNAMIC_FILTER_TYPE_COMMENT :
PlaylistRule->field = ITDB_SPLFIELD_COMMENT;
break;
case guDYNAMIC_FILTER_TYPE_PATH :
break;
case guDYNAMIC_FILTER_TYPE_YEAR :
PlaylistRule->field = ITDB_SPLFIELD_YEAR;
break;
case guDYNAMIC_FILTER_TYPE_RATING :
PlaylistRule->field = ITDB_SPLFIELD_RATING;
break;
case guDYNAMIC_FILTER_TYPE_LENGTH :
PlaylistRule->field = ITDB_SPLFIELD_TIME;
break;
case guDYNAMIC_FILTER_TYPE_PLAYCOUNT :
PlaylistRule->field = ITDB_SPLFIELD_PLAYCOUNT;
break;
case guDYNAMIC_FILTER_TYPE_LASTPLAY :
PlaylistRule->field = ITDB_SPLFIELD_LAST_PLAYED;
break;
case guDYNAMIC_FILTER_TYPE_ADDEDDATE :
PlaylistRule->field = ITDB_SPLFIELD_DATE_ADDED;
break;
case guDYNAMIC_FILTER_TYPE_TRACKNUMBER :
PlaylistRule->field = ITDB_SPLFIELD_TRACKNUMBER;
break;
case guDYNAMIC_FILTER_TYPE_BITRATE :
PlaylistRule->field = ITDB_SPLFIELD_BITRATE;
break;
case guDYNAMIC_FILTER_TYPE_SIZE :
PlaylistRule->field = ITDB_SPLFIELD_SIZE;
break;
case guDYNAMIC_FILTER_TYPE_DISK :
PlaylistRule->field = ITDB_SPLFIELD_DISC_NUMBER;
break;
case guDYNAMIC_FILTER_TYPE_HASARTWORK :
break;
}
switch( FilterItem->m_Type )
{
case guDYNAMIC_FILTER_TYPE_TITLE : // String
case guDYNAMIC_FILTER_TYPE_ARTIST :
case guDYNAMIC_FILTER_TYPE_ALBUMARTIST :
case guDYNAMIC_FILTER_TYPE_ALBUM :
case guDYNAMIC_FILTER_TYPE_GENRE :
case guDYNAMIC_FILTER_TYPE_COMPOSER :
case guDYNAMIC_FILTER_TYPE_COMMENT :
case guDYNAMIC_FILTER_TYPE_PATH :
case guDYNAMIC_FILTER_TYPE_DISK :
case guDYNAMIC_FILTER_TYPE_LABEL :
{
switch( FilterItem->m_Option )
{
case guDYNAMIC_FILTER_OPTION_STRING_CONTAINS :
PlaylistRule->action = ITDB_SPLACTION_CONTAINS;
break;
case guDYNAMIC_FILTER_OPTION_STRING_NOT_CONTAINS :
PlaylistRule->action = ITDB_SPLACTION_DOES_NOT_CONTAIN;
break;
case guDYNAMIC_FILTER_OPTION_STRING_IS :
PlaylistRule->action = ITDB_SPLACTION_IS_STRING;
break;
case guDYNAMIC_FILTER_OPTION_STRING_ISNOT :
PlaylistRule->action = ITDB_SPLACTION_IS_NOT;
break;
case guDYNAMIC_FILTER_OPTION_STRING_START_WITH :
PlaylistRule->action = ITDB_SPLACTION_STARTS_WITH;
break;
case guDYNAMIC_FILTER_OPTION_STRING_ENDS_WITH :
PlaylistRule->action = ITDB_SPLACTION_ENDS_WITH;
break;
}
PlaylistRule->string = strdup( FilterItem->m_Text.ToUTF8() );
PlaylistRule->fromvalue = 0;
PlaylistRule->tovalue = 0;
PlaylistRule->fromdate = 0;
PlaylistRule->todate = 0;
PlaylistRule->fromunits = 0;
PlaylistRule->tounits = 0;
break;
}
case guDYNAMIC_FILTER_TYPE_YEAR : // Year
case guDYNAMIC_FILTER_TYPE_RATING : // Numbers
case guDYNAMIC_FILTER_TYPE_PLAYCOUNT :
case guDYNAMIC_FILTER_TYPE_TRACKNUMBER :
case guDYNAMIC_FILTER_TYPE_BITRATE :
case guDYNAMIC_FILTER_TYPE_SIZE :
case guDYNAMIC_FILTER_TYPE_LENGTH : // Time
{
switch( FilterItem->m_Option )
{
case guDYNAMIC_FILTER_OPTION_NUMERIC_IS :
PlaylistRule->action = ITDB_SPLACTION_IS_INT;
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_ISNOT :
PlaylistRule->action = ITDB_SPLACTION_IS_NOT_INT;
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_AT_LEAST :
PlaylistRule->action = ITDB_SPLACTION_IS_GREATER_THAN;
break;
case guDYNAMIC_FILTER_OPTION_NUMERIC_AT_MOST :
PlaylistRule->action = ITDB_SPLACTION_IS_LESS_THAN;
break;
}
PlaylistRule->fromvalue = FilterItem->m_Number;
PlaylistRule->tovalue = FilterItem->m_Number;
PlaylistRule->fromdate = 0;
PlaylistRule->todate = 0;
PlaylistRule->fromunits = 1;
PlaylistRule->tounits = 1;
break;
}
case guDYNAMIC_FILTER_TYPE_LASTPLAY :
case guDYNAMIC_FILTER_TYPE_ADDEDDATE :
{
switch( FilterItem->m_Option )
{
case guDYNAMIC_FILTER_OPTION_DATE_IN_THE_LAST :
PlaylistRule->action = ITDB_SPLACTION_IS_IN_THE_LAST;
break;
case guDYNAMIC_FILTER_OPTION_DATE_BEFORE_THE_LAST :
PlaylistRule->action = ITDB_SPLACTION_IS_NOT_IN_THE_LAST;
break;
}
PlaylistRule->fromvalue = ITDB_SPL_DATE_IDENTIFIER;
PlaylistRule->tovalue = ITDB_SPL_DATE_IDENTIFIER;
PlaylistRule->fromdate = FilterItem->m_Number * -1;
PlaylistRule->todate = 0;
PlaylistRule->fromunits = DynPLDateOption2[ FilterItem->m_Option2 ];
PlaylistRule->tounits = 1;
break;
}
//case guDYNAMIC_FILTER_TYPE_HASARTWORK :
}
guLogMessage( wxT( "field : %i" ), PlaylistRule->field );
guLogMessage( wxT( "action : %08X" ), PlaylistRule->action );
if( PlaylistRule->string )
guLogMessage( wxT( "String : '%s'" ), wxString( PlaylistRule->string, wxConvUTF8 ).c_str() );
guLogMessage( wxT( "Values : %016llX %016llX" ), PlaylistRule->fromvalue, PlaylistRule->tovalue );
guLogMessage( wxT( "Dates : %016llX %016llX" ), PlaylistRule->fromdate, PlaylistRule->todate);
guLogMessage( wxT( "Units : %016llX %016llX" ), PlaylistRule->fromunits, PlaylistRule->tounits);
itdb_splr_validate( PlaylistRule );
guLogMessage( wxT( "Validated the Rule" ) );
}
}
itdb_spl_update( DynPlayList );
iPodFlush();
}
else
{
guLogMessage( wxT( "Could not create the playlist " ) );
}
return guDbLibrary::CreateDynamicPlayList( name, playlist );
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::UpdateDynamicPlayList( const int plid, const guDynPlayList * playlist )
{
wxString PlayListName = GetPlayListName( plid );
DeletePlayList( plid );
CreateDynamicPlayList( PlayListName, playlist );
}
// -------------------------------------------------------------------------------- //
Itdb_Track * guIpodLibrary::iPodFindTrack( const wxString &filename )
{
Itdb_Track * Track = NULL;
wxString FileName = filename;
if( FileName.StartsWith( m_PortableDevice->MountPath() ) )
{
FileName = FileName.Mid( m_PortableDevice->MountPath().Length() - 1 );
}
FileName.Replace( wxT( "/" ), wxT( ":" ) );
//guLogMessage( wxT( "Trying to find %s" ), FileName.c_str() );
GList * Tracks = m_iPodDb->tracks;
while( Tracks )
{
Itdb_Track * CurTrack = ( Itdb_Track * ) Tracks->data;
//guLogMessage( wxT( "Checking: '%s" ), wxString( CurTrack->ipod_path, wxConvUTF8 ).c_str() );
if( wxString( CurTrack->ipod_path, wxConvUTF8 ) == FileName )
{
Track = CurTrack;
break;
}
Tracks = Tracks->next;
}
return Track;
}
// -------------------------------------------------------------------------------- //
Itdb_Track * guIpodLibrary::iPodFindTrack( const wxString &artist, const wxString &albumartist, const wxString &album, const wxString &title )
{
Itdb_Track * Track = NULL;
GList * Tracks = m_iPodDb->tracks;
while( Tracks )
{
Itdb_Track * CurTrack = ( Itdb_Track * ) Tracks->data;
if( ( albumartist.IsEmpty() ? ( wxString( CurTrack->artist, wxConvUTF8 ) == artist ) :
( wxString( CurTrack->albumartist, wxConvUTF8 ) == albumartist ) ) &&
( wxString( CurTrack->album, wxConvUTF8 ) == album ) &&
( wxString( CurTrack->title, wxConvUTF8 ) == title ) )
{
Track = CurTrack;
break;
}
Tracks = Tracks->next;
}
return Track;
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::iPodRemoveTrack( Itdb_Track * track )
{
if( track )
{
GList * Playlists = m_iPodDb->playlists;
while( Playlists )
{
Itdb_Playlist * CurPlaylist = ( Itdb_Playlist * ) Playlists->data;
if( itdb_playlist_contains_track( CurPlaylist, track ) )
{
itdb_playlist_remove_track( CurPlaylist, track );
}
Playlists = Playlists->next;
}
itdb_track_remove_thumbnails( track );
itdb_track_remove( track );
}
}
// -------------------------------------------------------------------------------- //
void guIpodLibrary::iPodRemoveTrack( const wxString &filename )
{
Itdb_Track * Track = iPodFindTrack( filename );
iPodRemoveTrack( Track );
if( !wxRemoveFile( filename ) )
guLogMessage( wxT( "Couldnt remove the file '%s'" ), filename.c_str() );
}
// -------------------------------------------------------------------------------- //
int guIpodLibrary::UpdateSong( const guTrack &track, const bool allowrating )
{
wxString query = wxString::Format( wxT( "UPDATE songs SET song_name = '%s', " \
"song_genreid = %u, song_genre = '%s', " \
"song_artistid = %u, song_artist = '%s', " \
"song_albumartistid = %u, song_albumartist = '%s', " \
"song_albumid = %u, song_album = '%s', " \
"song_pathid = %u, song_path = '%s', " \
"song_filename = '%s', song_format = '%s', " \
"song_number = %u, song_year = %u, " \
"song_composerid = %u, song_composer = '%s', " \
"song_comment = '%s', song_coverid = %i, song_disk = '%s', " \
"song_length = %u, song_offset = %u, song_bitrate = %u, " \
"song_rating = %i, song_filesize = %u, " \
"song_lastplay = %u, song_addedtime = %u, " \
"song_playcount = %u " \
"WHERE song_id = %u;" ),
escape_query_str( track.m_SongName ).c_str(),
track.m_GenreId,
escape_query_str( track.m_GenreName ).c_str(),
track.m_ArtistId,
escape_query_str( track.m_ArtistName ).c_str(),
track.m_AlbumArtistId,
escape_query_str( track.m_AlbumArtist ).c_str(),
track.m_AlbumId,
escape_query_str( track.m_AlbumName ).c_str(),
track.m_PathId,
escape_query_str( track.m_Path ).c_str(),
escape_query_str( track.m_FileName ).c_str(),
escape_query_str( track.m_FileName.AfterLast( '.' ) ).c_str(),
track.m_Number,
track.m_Year,
track.m_ComposerId, //escape_query_str( track.m_Composer ).c_str(),
escape_query_str( track.m_Composer ).c_str(),
escape_query_str( track.m_Comments ).c_str(),
track.m_CoverId,
escape_query_str( track.m_Disk ).c_str(),
track.m_Length,
0, //track.m_Offset,
track.m_Bitrate,
track.m_Rating,
track.m_FileSize,
track.m_LastPlay,
track.m_AddedTime,
track.m_PlayCount,
track.m_SongId );
//guLogMessage( wxT( "%s" ), query.c_str() );
return ExecuteUpdate( query );
}
// -------------------------------------------------------------------------------- //
// guIpodLibraryUpdate
// -------------------------------------------------------------------------------- //
guIpodLibraryUpdate::guIpodLibraryUpdate( guMediaVieweriPodDevice * mediaviewer, const int gaugeid )
{
m_MediaViewer = mediaviewer;
m_GaugeId = gaugeid;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY - 30 );
Run();
}
}
// -------------------------------------------------------------------------------- //
guIpodLibraryUpdate::~guIpodLibraryUpdate()
{
if( !TestDestroy() )
{
m_MediaViewer->UpdateFinished();
}
wxCommandEvent GaugeEvent( wxEVT_MENU, ID_STATUSBAR_GAUGE_REMOVE );
GaugeEvent.SetInt( m_GaugeId );
wxPostEvent( guMainFrame::GetMainFrame(), GaugeEvent );
}
extern "C" {
extern gboolean gdk_pixbuf_save_to_buffer( GdkPixbuf *pixbuf,
gchar **buffer,
gsize *buffer_size,
const char *type,
GError **error,
... );
}
// -------------------------------------------------------------------------------- //
guIpodLibraryUpdate::ExitCode guIpodLibraryUpdate::Entry( void )
{
wxArrayPtrVoid CoveriPodTracks;
wxArrayInt CoverAlbumIds;
guIpodLibrary * Db = ( guIpodLibrary * ) m_MediaViewer->GetDb();
Itdb_iTunesDB * iPodDb = Db->GetiPodDb();
if( iPodDb )
{
//Db->ExecuteUpdate( wxT( "DELETE FROM songs" ) );
guPortableMediaDevice * PortableMediaDevice = m_MediaViewer->GetPortableMediaDevice();
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
wxCommandEvent GaugeEvent( wxEVT_MENU, ID_STATUSBAR_GAUGE_SETMAX );
GaugeEvent.SetInt( m_GaugeId );
GaugeEvent.SetExtraLong( itdb_tracks_number( iPodDb ) );
wxPostEvent( MainFrame, GaugeEvent );
GaugeEvent.SetId( ID_STATUSBAR_GAUGE_UPDATE );
int TrackIndex = 0;
// Add any missing track to the database or update the existing ones
GList * Tracks = iPodDb->tracks;
while( !TestDestroy() && Tracks )
{
Itdb_Track * iPodTrack = ( Itdb_Track * ) Tracks->data;
if( iPodTrack )
{
guTrack Track;
Track.m_SongName = wxString( iPodTrack->title, wxConvUTF8 );
Track.m_ArtistName = wxString( iPodTrack->artist, wxConvUTF8 );
Track.m_ArtistId = Db->GetArtistId( Track.m_ArtistName );
Track.m_GenreName = wxString( iPodTrack->genre, wxConvUTF8 );
Track.m_GenreId = Db->GetGenreId( Track.m_GenreName );
Track.m_Composer = wxString( iPodTrack->composer, wxConvUTF8 );
Track.m_ComposerId = Db->GetComposerId( Track.m_Composer );
Track.m_Comments = wxString( iPodTrack->comment, wxConvUTF8 );
Track.m_AlbumArtist = wxString( iPodTrack->albumartist, wxConvUTF8 );
Track.m_AlbumArtistId = Db->GetAlbumArtistId( Track.m_AlbumArtist );
Track.m_AlbumName = wxString( iPodTrack->album, wxConvUTF8 );
Track.m_FileSize = iPodTrack->size;
Track.m_Length = iPodTrack->tracklen;
if( iPodTrack->cd_nr || iPodTrack->cds )
{
Track.m_Disk = wxString::Format( wxT( "%u/%u" ), iPodTrack->cd_nr, iPodTrack->cds );
}
Track.m_Number = iPodTrack->track_nr;
Track.m_Bitrate = iPodTrack->bitrate;
Track.m_Year = iPodTrack->year;
Track.m_Rating = iPodTrack->rating / ITDB_RATING_STEP;
Track.m_PlayCount = iPodTrack->playcount;
Track.m_AddedTime = iPodTrack->time_added;
Track.m_LastPlay = iPodTrack->time_played;
Track.m_Path = PortableMediaDevice->MountPath() + wxString( iPodTrack->ipod_path, wxConvUTF8 ).Mid( 1 );
Track.m_Path.Replace( wxT( ":" ), wxT( "/" ) );
Track.m_FileName = Track.m_Path.AfterLast( wxT( '/' ) );
Track.m_Path = wxPathOnly( Track.m_Path ) + wxT( "/" );
Track.m_PathId = Db->GetPathId( Track.m_Path );
Track.m_SongId = Db->GetSongId( Track.m_FileName, Track.m_PathId, iPodTrack->time_added );
Track.m_AlbumId = Db->GetAlbumId( Track.m_AlbumName, Track.m_ArtistName, Track.m_AlbumArtist, Track.m_Disk );
Db->UpdateSong( Track, true );
if( itdb_track_has_thumbnails( iPodTrack ) )
{
if( CoverAlbumIds.Index( Track.m_AlbumId ) == wxNOT_FOUND )
{
CoveriPodTracks.Add( iPodTrack );
CoverAlbumIds.Add( Track.m_AlbumId );
}
}
}
Tracks = Tracks->next;
//
TrackIndex++;
GaugeEvent.SetExtraLong( TrackIndex );
wxPostEvent( MainFrame, GaugeEvent );
}
// Find all tracks that have been removed
wxString FileName;
wxArrayInt SongsToDel;
wxSQLite3ResultSet dbRes;
dbRes = Db->ExecuteQuery( wxT( "SELECT DISTINCT song_id, song_filename, song_path FROM songs " ) );
while( !TestDestroy() && dbRes.NextRow() )
{
FileName = dbRes.GetString( 2 ) + dbRes.GetString( 1 );
if( !wxFileExists( FileName ) )
{
SongsToDel.Add( dbRes.GetInt( 0 ) );
}
}
dbRes.Finalize();
// Add the covers to the albums
int Count;
if( ( Count = CoveriPodTracks.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
if( TestDestroy() )
break;
Itdb_Track * iPodTrack = ( Itdb_Track * ) CoveriPodTracks[ Index ];
int AlbumId = CoverAlbumIds[ Index ];
GdkPixbuf * Pixbuf = ( GdkPixbuf * ) itdb_track_get_thumbnail( iPodTrack, -1, -1 );
if( Pixbuf )
{
void * Buffer = NULL;
gsize BufferSize = 0;
if( gdk_pixbuf_save_to_buffer( Pixbuf, ( gchar ** ) &Buffer, &BufferSize, "jpeg", NULL, "quality", "100", NULL ) )
{
wxMemoryInputStream ImageStream( Buffer, BufferSize );
wxImage CoverImage( ImageStream, wxBITMAP_TYPE_JPEG );
if( CoverImage.IsOk() )
{
Db->SetAlbumCover( AlbumId, CoverImage );
}
else
{
guLogMessage( wxT( "Error in image from ipod..." ) );
}
g_free( Buffer );
}
else
{
guLogMessage( wxT( "Couldnt save to a buffer the pixbuf for album %i" ), AlbumId );
}
g_object_unref( Pixbuf );
}
else
{
guLogMessage( wxT( "Couldnt get the pixbuf for album %i" ), AlbumId );
}
}
}
// Delete all playlists
Db->ExecuteUpdate( wxT( "DELETE FROM playlists;" ) );
Db->ExecuteUpdate( wxT( "DELETE FROM plsets;" ) );
GList * Playlists = iPodDb->playlists;
while( !TestDestroy() && Playlists )
{
Itdb_Playlist * Playlist = ( Itdb_Playlist * ) Playlists->data;
if( Playlist && !Playlist->podcastflag && !Playlist->type )
{
wxString PlaylistName = wxString( Playlist->name, wxConvUTF8 );
guLogMessage( wxT( "Playlist: '%s'" ), PlaylistName.c_str() );
if( !Playlist->is_spl ) // Its not a smart playlist
{
wxArrayInt PlaylistTrackIds;
Tracks = Playlist->members;
while( Tracks )
{
Itdb_Track * PlaylistTrack = ( Itdb_Track * ) Tracks->data;
if( PlaylistTrack )
{
wxString Path = PortableMediaDevice->MountPath() + wxString( PlaylistTrack->ipod_path, wxConvUTF8 ).Mid( 1 );
Path.Replace( wxT( ":" ), wxT( "/" ) );
wxString FileName = Path.AfterLast( wxT( '/' ) );
Path = wxPathOnly( Path ) + wxT( "/" );
int PathId = Db->GetPathId( Path );
int TrackId = Db->GetSongId( FileName, PathId, PlaylistTrack->time_added );
if( TrackId )
{
PlaylistTrackIds.Add( TrackId );
}
}
Tracks = Tracks->next;
}
Db->CreateStaticPlayList( PlaylistName, PlaylistTrackIds, true );
}
else // Its a dynamic playlist
{
guDynPlayList NewPlayList;
bool ErrorInPlaylist = false;
guLogMessage( wxT( "Found a dynamic playlist '%s' with %i tracks" ), PlaylistName.c_str(), Playlist->num );
guLogMessage( wxT( "id : %i" ), Playlist->id );
guLogMessage( wxT( "sortorder : %i" ), Playlist->sortorder );
NewPlayList.m_Sorted = ( Playlist->sortorder != ITDB_PSO_MANUAL );
switch( Playlist->sortorder )
{
case ITDB_PSO_MANUAL :
break;
// case ITDB_PSO_BIRATE :
// case ITDB_PSO_FILETYPE :
// case ITDB_PSO_TRACK_NR :
// case ITDB_PSO_SIZE :
// case ITDB_PSO_SAMPLERATE :
// case ITDB_PSO_COMMENT :
// case ITDB_PSO_EQUALIZER :
// case ITDB_PSO_CD_NR :
// case ITDB_PSO_BPM :
case ITDB_PSO_GROUPING :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_LABEL;
break;
// case ITDB_PSO_CATEGORY :
// case ITDB_PSO_DESCRIPTION :
// break;
case ITDB_PSO_TITLE :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_TITLE;
break;
case ITDB_PSO_ALBUM :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_ALBUM;
break;
case ITDB_PSO_ARTIST :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_ARTIST;
break;
case ITDB_PSO_GENRE :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_GENRE;
break;
case ITDB_PSO_TIME_MODIFIED :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_GENRE;
break;
case ITDB_PSO_TIME :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_LENGTH;
break;
case ITDB_PSO_YEAR :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_YEAR;
break;
case ITDB_PSO_TIME_ADDED :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_ADDEDDATE;
break;
case ITDB_PSO_COMPOSER :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_COMPOSER;
break;
case ITDB_PSO_PLAYCOUNT :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_PLAYCOUNT;
break;
case ITDB_PSO_TIME_PLAYED :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_LASTPLAY;
break;
case ITDB_PSO_RATING :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_RATING;
break;
case ITDB_PSO_RELEASE_DATE :
NewPlayList.m_SortType = guDYNAMIC_FILTER_ORDER_YEAR;
break;
default :
ErrorInPlaylist = true;
guLogMessage( wxT( "Sorting not supported %i" ), Playlist->sortorder );
break;
}
Itdb_SPLPref * PlaylistPref = &Playlist->splpref;
guLogMessage( wxT( "liveupdate : %i" ), PlaylistPref->liveupdate );
guLogMessage( wxT( "checkrules : %i" ), PlaylistPref->checkrules );
guLogMessage( wxT( "checklimits : %i" ), PlaylistPref->checklimits );
guLogMessage( wxT( "limittype : %i" ), PlaylistPref->limittype );
if( PlaylistPref->checklimits )
{
NewPlayList.m_Limited = true;
NewPlayList.m_LimitValue = PlaylistPref->limitvalue;
switch( PlaylistPref->limittype )
{
case ITDB_LIMITTYPE_MINUTES :
NewPlayList.m_LimitType = guDYNAMIC_FILTER_LIMIT_MINUTES;
break;
case ITDB_LIMITTYPE_MB :
NewPlayList.m_LimitType = guDYNAMIC_FILTER_LIMIT_MEGABYTES;
break;
case ITDB_LIMITTYPE_SONGS :
NewPlayList.m_LimitType = guDYNAMIC_FILTER_LIMIT_TRACKS;
break;
case ITDB_LIMITTYPE_HOURS :
NewPlayList.m_LimitType = guDYNAMIC_FILTER_LIMIT_MINUTES;
NewPlayList.m_LimitValue *= 60;
break;
case ITDB_LIMITTYPE_GB :
NewPlayList.m_LimitType = guDYNAMIC_FILTER_LIMIT_GIGABYTES;
break;
}
}
Itdb_SPLRules * PlaylistRules = &Playlist->splrules;
guLogMessage( wxT( "operator : %i" ), PlaylistRules->match_operator );
if( PlaylistRules->match_operator == ITDB_SPLMATCH_OR )
NewPlayList.m_AnyOption = true;
GList * Rules = PlaylistRules->rules;
int RuleCount = 0;
while( !ErrorInPlaylist && Rules && ( RuleCount < PlaylistPref->checkrules ) )
{
guLogMessage( wxT( "###===---Rule---===###" ) );
Itdb_SPLRule * PlaylistRule = ( Itdb_SPLRule * ) Rules->data;
if( PlaylistRule )
{
guFilterItem * FilterItem = new guFilterItem();
guLogMessage( wxT( "field : %i" ), PlaylistRule->field );
guLogMessage( wxT( "action : %08X" ), PlaylistRule->action );
if( PlaylistRule->string )
guLogMessage( wxT( "String : '%s'" ), wxString( PlaylistRule->string, wxConvUTF8 ).c_str() );
guLogMessage( wxT( "Values : %016llX %016llX" ), PlaylistRule->fromvalue, PlaylistRule->tovalue );
guLogMessage( wxT( "Dates : %016llX %016llX" ), PlaylistRule->fromdate, PlaylistRule->todate);
guLogMessage( wxT( "Units : %016llX %016llX" ), PlaylistRule->fromunits, PlaylistRule->tounits);
switch( PlaylistRule->field )
{
case ITDB_SPLFIELD_SONG_NAME :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_TITLE;
break;
case ITDB_SPLFIELD_ALBUM :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_ALBUM;
break;
case ITDB_SPLFIELD_ARTIST :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_ARTIST;
break;
case ITDB_SPLFIELD_BITRATE :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_BITRATE;
break;
case ITDB_SPLFIELD_YEAR :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_YEAR;
break;
case ITDB_SPLFIELD_GENRE :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_GENRE;
break;
case ITDB_SPLFIELD_TRACKNUMBER :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_TRACKNUMBER;
break;
case ITDB_SPLFIELD_SIZE :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_SIZE;
break;
case ITDB_SPLFIELD_TIME :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_LENGTH;
break;
case ITDB_SPLFIELD_COMMENT :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_COMMENT;
break;
case ITDB_SPLFIELD_DATE_ADDED :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_ADDEDDATE;
break;
case ITDB_SPLFIELD_COMPOSER :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_COMPOSER;
break;
case ITDB_SPLFIELD_PLAYCOUNT :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_PLAYCOUNT;
break;
case ITDB_SPLFIELD_LAST_PLAYED :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_LASTPLAY;
break;
case ITDB_SPLFIELD_DISC_NUMBER :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_DISK;
break;
case ITDB_SPLFIELD_RATING :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_RATING;
break;
case ITDB_SPLFIELD_ALBUMARTIST :
FilterItem->m_Type = guDYNAMIC_FILTER_TYPE_ALBUMARTIST;
break;
default :
ErrorInPlaylist = true;
break;
}
switch( PlaylistRule->action )
{
case ITDB_SPLACTION_IS_INT :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_IS;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
case ITDB_SPLACTION_IS_GREATER_THAN :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_AT_LEAST;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
case ITDB_SPLACTION_IS_LESS_THAN :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_AT_MOST;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
//case ITDB_SPLACTION_IS_IN_THE_RANGE :
//case ITDB_SPLACTION_IS_IN_THE_LAST :
// break;
//case ITDB_SPLACTION_BINARY_AND :
case ITDB_SPLACTION_IS_STRING :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_IS;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
case ITDB_SPLACTION_CONTAINS :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_CONTAINS;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
case ITDB_SPLACTION_STARTS_WITH :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_START_WITH;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
case ITDB_SPLACTION_ENDS_WITH :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_ENDS_WITH;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
case ITDB_SPLACTION_IS_NOT_INT :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_ISNOT;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
case ITDB_SPLACTION_IS_NOT_GREATER_THAN :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_AT_MOST;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
case ITDB_SPLACTION_IS_NOT_LESS_THAN :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_NUMERIC_AT_LEAST;
FilterItem->m_Number = PlaylistRule->fromvalue;
break;
//case ITDB_SPLACTION_IS_NOT_IN_THE_RANGE :
//case ITDB_SPLACTION_IS_NOT_IN_THE_LAST :
case ITDB_SPLACTION_IS_NOT :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_ISNOT;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
case ITDB_SPLACTION_DOES_NOT_CONTAIN :
FilterItem->m_Option = guDYNAMIC_FILTER_OPTION_STRING_NOT_CONTAINS;
FilterItem->m_Text = wxString( PlaylistRule->string, wxConvUTF8 );
break;
//case ITDB_SPLACTION_DOES_NOT_START_WITH :
//case ITDB_SPLACTION_DOES_NOT_END_WITH :
default :
ErrorInPlaylist = true;
break;
}
if( !ErrorInPlaylist )
{
NewPlayList.m_Filters.Add( FilterItem );
}
else
{
guLogMessage( wxT( "The playlist have been discarded by rule %08X %08X" ), PlaylistRule->field, PlaylistRule->action );
guLogMessage( wxT( "Value: %016llX %016llX" ), PlaylistRule->fromvalue, PlaylistRule->tovalue );
guLogMessage( wxT( "Dates: %016llX %016llX" ), PlaylistRule->fromdate, PlaylistRule->todate);
guLogMessage( wxT( "Units: %016llX %016llX" ), PlaylistRule->fromunits, PlaylistRule->tounits);
delete FilterItem;
}
}
Rules = Rules->next;
RuleCount++;
}
if( !ErrorInPlaylist )
{
// Save the dynamic playlist now
Db->CreateDynamicPlayList( PlaylistName, &NewPlayList, true );
}
}
}
else
{
guLogMessage( wxT( "Playlist was podcast or master" ) );
}
Playlists = Playlists->next;
}
wxCommandEvent evt( wxEVT_MENU, ID_PLAYLIST_UPDATED );
//evt.SetClientData( ( void * ) m_iPodPanel );
wxPostEvent( MainFrame, evt );
// Clean all the deleted items
if( !TestDestroy() )
{
wxArrayString Queries;
if( SongsToDel.Count() )
{
Queries.Add( wxT( "DELETE FROM songs WHERE " ) + ArrayToFilter( SongsToDel, wxT( "song_id" ) ) );
}
// Delete all posible orphan entries
Queries.Add( wxT( "DELETE FROM covers WHERE cover_id NOT IN ( SELECT DISTINCT song_coverid FROM songs );" ) );
Queries.Add( wxT( "DELETE FROM plsets WHERE plset_type = 0 AND plset_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" ) );
Queries.Add( wxT( "DELETE FROM settags WHERE settag_songid NOT IN ( SELECT DISTINCT song_id FROM songs );" ) );
int Count = Queries.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( TestDestroy() )
break;
//guLogMessage( wxT( "Executing: '%s'" ), Queries[ Index ].c_str() );
Db->ExecuteUpdate( Queries[ Index ] );
}
}
}
return 0;
}
// -------------------------------------------------------------------------------- //
// guMediaVieweriPodDevice
// -------------------------------------------------------------------------------- //
guMediaVieweriPodDevice::guMediaVieweriPodDevice( wxWindow * parent, guMediaCollection &mediacollection,
const int basecmd, guMainFrame * mainframe, const int mode,
guPlayerPanel * playerpanel, guGIO_Mount * mount ) :
guMediaViewerPortableDeviceBase( parent, mediacollection, basecmd, mainframe, mode, playerpanel, mount )
{
m_PendingSaving = false;
InitMediaViewer( mode );
}
// -------------------------------------------------------------------------------- //
guMediaVieweriPodDevice::~guMediaVieweriPodDevice()
{
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::LoadMediaDb( void )
{
Itdb_iTunesDB * iPodDb = itdb_parse( m_PortableDevice->MountPath().mb_str( wxConvFile ), NULL );
m_PortableDevice->SetType( guPORTABLE_MEDIA_TYPE_IPOD );
m_Db = new guIpodLibrary( guPATH_COLLECTIONS + m_MediaCollection->m_UniqueId + wxT( "/guayadeque.db" ), m_PortableDevice, iPodDb );
m_Db->SetMediaViewer( this );
guLogMessage( wxT( "Detected an Ipod with %i tracks and %i playlists" ), itdb_tracks_number( iPodDb ), itdb_playlists_number( iPodDb ) );
Itdb_Device * iPodDevice = iPodDb->device;
if( iPodDevice )
{
//guLogMessage( wxT( "Artwork support : %i" ), itdb_device_supports_artwork( iPodDevice ) );
const Itdb_IpodInfo * iPodInfo = itdb_device_get_ipod_info( iPodDevice );
if( iPodInfo )
{
guLogMessage( wxT( "Model Number : %s" ), wxString( iPodInfo->model_number, wxConvUTF8 ).c_str() );
guLogMessage( wxT( "Capacity : %.0f" ), iPodInfo->capacity );
guLogMessage( wxT( "Model Name : %s" ), wxString( itdb_info_get_ipod_model_name_string( iPodInfo->ipod_model ), wxConvUTF8 ).c_str() );
guLogMessage( wxT( "Generation : %s" ), wxString( itdb_info_get_ipod_generation_string( iPodInfo->ipod_generation ), wxConvUTF8 ).c_str() );
}
}
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::CreateContextMenu( wxMenu * menu, const int windowid )
{
wxMenu * Menu = new wxMenu();
wxMenuItem * MenuItem;
int BaseCommand = GetBaseCommand();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_UPDATE_LIBRARY, _( "Update" ), _( "Update the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_RESCAN_LIBRARY, _( "Rescan" ), _( "Rescan the collection library" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_SEARCH_COVERS, _( "Search Covers" ), _( "Search the collection missing covers" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( menu, BaseCommand + guCOLLECTION_ACTION_UNMOUNT, _( "Unmount" ), _( "Unmount the device" ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, BaseCommand + guCOLLECTION_ACTION_VIEW_PROPERTIES, _( "Properties" ), _( "Show collection properties" ), wxITEM_NORMAL );
Menu->Append( MenuItem );
menu->AppendSeparator();
menu->AppendSubMenu( Menu, m_MediaCollection->m_Name );
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::HandleCommand( const int command )
{
if( command == guCOLLECTION_ACTION_UNMOUNT )
{
if( m_PortableDevice->CanUnmount() )
{
m_PortableDevice->Unmount();
}
}
else
{
guMediaViewer::HandleCommand( command );
}
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::EditProperties( void )
{
guPortableMediaProperties * PortableMediaProperties = new guPortableMediaProperties( this, m_PortableDevice );
if( PortableMediaProperties )
{
if( PortableMediaProperties->ShowModal() == wxID_OK )
{
PortableMediaProperties->WriteConfig();
//
// UpdateCollectionProperties();
}
PortableMediaProperties->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::UpdateLibrary( void )
{
int GaugeId;
GaugeId = m_MainFrame->AddGauge( m_MediaCollection->m_Name );
if( m_UpdateThread )
{
m_UpdateThread->Pause();
m_UpdateThread->Delete();
}
m_UpdateThread = new guIpodLibraryUpdate( this, GaugeId );
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::CleanLibrary( void )
{
wxCommandEvent event( wxEVT_MENU, ID_LIBRARY_CLEANFINISHED );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
int Count = tracks->Count();
for( int Index = 0; Index < Count; Index++ )
{
tracks->Item( Index ).m_Type = guTRACK_TYPE_IPOD;
}
}
// -------------------------------------------------------------------------------- //
bool guMediaVieweriPodDevice::SetAlbumCover( const int albumid, const wxString &albumpath, wxImage * coverimg )
{
guTrackArray Tracks;
wxArrayInt Albums;
Albums.Add( albumid );
m_Db->GetAlbumsSongs( Albums, &Tracks );
int Count;
if( ( Count = Tracks.Count() ) )
{
int MaxSize = GetCoverMaxSize();
if( MaxSize )
{
coverimg->Rescale( MaxSize, MaxSize, wxIMAGE_QUALITY_HIGH );
}
wxString TmpFile = wxFileName::CreateTempFileName( wxT( "guTmpImg_" ) );
wxRemoveFile( TmpFile );
TmpFile += wxT( ".jpg" );
if( coverimg->SaveFile( TmpFile, wxBITMAP_TYPE_JPEG ) )
{
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = ( ( guIpodLibrary * ) m_Db )->iPodFindTrack( Tracks[ Index ].m_FileName );
if( iPodTrack )
{
if( itdb_track_has_thumbnails( iPodTrack ) )
{
itdb_artwork_remove_thumbnails( iPodTrack->artwork );
}
if( !itdb_track_set_thumbnails( iPodTrack, TmpFile.mb_str( wxConvFile ) ) )
guLogMessage( wxT( "Couldnt set the cover image %s" ), TmpFile.c_str() );
}
if( m_PortableDevice->CoverFormats() & guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED )
{
guTagSetPicture( Tracks[ Index ].m_FileName, coverimg );
}
}
( ( guIpodLibrary * ) m_Db )->iPodFlush();
wxRemoveFile( TmpFile );
m_Db->SetAlbumCover( albumid, * coverimg );
}
else
{
guLogMessage( wxT( "Couldnt save the temporary image file" ) );
}
}
return true;
}
// -------------------------------------------------------------------------------- //
bool guMediaVieweriPodDevice::SetAlbumCover( const int albumid, const wxString &albumpath, wxString &coverpath )
{
wxURI Uri( coverpath );
if( Uri.IsReference() )
{
wxImage CoverImage( coverpath );
if( CoverImage.IsOk() )
{
return SetAlbumCover( albumid, albumpath, &CoverImage );
}
else
{
guLogError( wxT( "Could not load the imate '%s'" ), coverpath.c_str() );
}
}
else
{
wxString TmpFile = wxFileName::CreateTempFileName( wxT( "guTmpImg_" ) );
wxRemoveFile( TmpFile );
TmpFile += wxT( ".jpg" );
if( DownloadImage( coverpath, TmpFile, wxBITMAP_TYPE_JPEG ) )
{
bool Result = SetAlbumCover( albumid, albumpath, TmpFile );
wxRemoveFile( TmpFile );
return Result;
}
else
{
guLogError( wxT( "Failed to download file '%s'" ), coverpath.c_str() );
}
}
return false;
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::DeleteAlbumCover( const int albumid )
{
guTrackArray Tracks;
wxArrayInt Albums;
Albums.Add( albumid );
m_Db->GetAlbumsSongs( Albums, &Tracks );
int Count;
if( ( Count = Tracks.Count() ) )
{
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = ( ( guIpodLibrary * ) m_Db )->iPodFindTrack( Tracks[ Index ].m_FileName );
if( iPodTrack )
{
guLogMessage( wxT( "Deleting cover for track '%s'" ), wxString( iPodTrack->ipod_path, wxConvUTF8 ).c_str() );
itdb_artwork_remove_thumbnails( iPodTrack->artwork );
}
}
( ( guIpodLibrary * ) m_Db )->iPodFlush();
}
guMediaViewer::DeleteAlbumCover( albumid );
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::DeleteTracks( const guTrackArray * tracks )
{
int Count;
if( ( Count = tracks->Count() ) )
{
m_Db->DeleteLibraryTracks( tracks, false );
Itdb_iTunesDB * iPodDb = ( ( guIpodLibrary * ) m_Db )->GetiPodDb();
Itdb_Playlist * MasterPlaylist = itdb_playlist_mpl( iPodDb );
for( int Index = 0; Index < Count; Index++ )
{
Itdb_Track * iPodTrack = ( ( guIpodLibrary * ) m_Db )->iPodFindTrack( tracks->Item( Index ).m_FileName );
if( iPodTrack )
{
itdb_playlist_remove_track( MasterPlaylist, iPodTrack );
itdb_track_remove( iPodTrack );
}
//
if( !wxRemoveFile( tracks->Item( Index ).m_FileName ) )
{
guLogMessage( wxT( "Couldnt remove file %s" ), tracks->Item( Index ).m_FileName.c_str() );
}
}
( ( guIpodLibrary * ) m_Db )->iPodFlush();
}
}
// -------------------------------------------------------------------------------- //
int guMediaVieweriPodDevice::CopyTo( const guTrack * track, wxString &filename )
{
if( !track )
return 0;
Itdb_Track * iPodTrack = itdb_track_new();
iPodTrack->title = strdup( track->m_SongName.ToUTF8() );
iPodTrack->album = strdup( track->m_AlbumName.ToUTF8() );
iPodTrack->artist = strdup( track->m_ArtistName.ToUTF8() );
iPodTrack->genre = strdup( track->m_GenreName.ToUTF8() );
iPodTrack->comment = strdup( track->m_Comments.ToUTF8() );
iPodTrack->composer = strdup( track->m_Composer.ToUTF8() );
iPodTrack->albumartist = strdup( track->m_AlbumArtist.ToUTF8() );
iPodTrack->size = track->m_FileSize;
iPodTrack->tracklen = track->m_Length;
iPodTrack->track_nr = track->m_Number;
guStrDiskToDiskNum( track->m_Disk, iPodTrack->cd_nr, iPodTrack->cds );
iPodTrack->bitrate = track->m_Bitrate;
iPodTrack->year = track->m_Year;
iPodTrack->BPM = 0;
iPodTrack->rating = ( track->m_Rating == wxNOT_FOUND ) ? 0 : track->m_Rating * ITDB_RATING_STEP;
iPodTrack->playcount = 0;
iPodTrack->type1 = 0;
iPodTrack->type2 = track->m_Format == wxT( "mp3" ) ? 1 : 0;
iPodTrack->compilation = 0; //!track->m_AlbumArtist.IsEmpty();
iPodTrack->mediatype = ITDB_MEDIATYPE_AUDIO;
iPodTrack->time_added = track->m_AddedTime;
wxString CoverPath;
if( track->m_CoverId && track->m_MediaViewer )
{
guDbLibrary * TrackDb = track->m_MediaViewer->GetDb();
if( TrackDb )
{
CoverPath = TrackDb->GetCoverPath( track->m_CoverId );
}
if( wxFileExists( CoverPath ) )
{
if( !itdb_track_set_thumbnails( iPodTrack, CoverPath.mb_str( wxConvFile ) ) )
guLogMessage( wxT( "Could not add cover to the ipod track" ) );
}
}
Itdb_iTunesDB * iPodDb = ( ( guIpodLibrary * ) m_Db )->GetiPodDb();
// Add the track to the iPod Database
itdb_track_add( iPodDb, iPodTrack, wxNOT_FOUND );
// Add th etrack to the master playlist
Itdb_Playlist * MasterPlaylist = itdb_playlist_mpl( iPodDb );
itdb_playlist_add_track( MasterPlaylist, iPodTrack, wxNOT_FOUND );
int FileFormat = guGetTranscodeFileFormat( track->m_FileName.Lower().AfterLast( wxT( '.' ) ) );
wxString TmpFile;
// Copy the track file
if( track->m_Offset ||
!( m_PortableDevice->AudioFormats() & FileFormat ) ||
( m_PortableDevice->TranscodeScope() == guPORTABLEMEDIA_TRANSCODE_SCOPE_ALWAYS ) )
{
// We need to transcode the file to a temporary file and then copy it
guLogMessage( wxT( "guIpodMediaLibPanel Transcode File start" ) );
TmpFile = wxFileName::CreateTempFileName( wxT( "guTrcde_" ) );
wxRemoveFile( TmpFile );
TmpFile += wxT( "." ) + guTranscodeFormatString( m_PortableDevice->TranscodeFormat() );
guTranscodeThread * TranscodeThread = new guTranscodeThread( track, TmpFile.wchar_str(), m_PortableDevice->TranscodeFormat(), m_PortableDevice->TranscodeQuality() );
if( TranscodeThread && TranscodeThread->IsOk() )
{
// TODO : Make a better aproach to be sure its running
// This need to be called from a thread
wxThread::Sleep( 1000 );
while( TranscodeThread->IsTranscoding() )
{
wxThread::Sleep( 200 );
}
}
if( !TranscodeThread->IsOk() )
{
guLogMessage( wxT( "Error transcoding the file '%s'" ), track->m_FileName.c_str() );
wxRemoveFile( TmpFile );
return wxNOT_FOUND;
}
iPodTrack->bitrate = guGetMp3QualityBitRate( m_PortableDevice->TranscodeQuality() );
iPodTrack->size = guGetFileSize( TmpFile );
//wxString guTagGetLyrics( const wxString &filename )
if( !track->m_Offset )
{
wxString LyricText = guTagGetLyrics( track->m_FileName );
if( !LyricText.IsEmpty() )
{
guTagSetLyrics( TmpFile, LyricText );
}
}
}
else // The file is supported
{
TmpFile = wxFileName::CreateTempFileName( wxT( "guTrcde_" ) );
wxRemoveFile( TmpFile );
TmpFile += wxT( "." ) + track->m_FileName.Lower().AfterLast( wxT( '.' ) );
if( !wxCopyFile( track->m_FileName, TmpFile ) )
{
guLogMessage( wxT( "Error copying file '%s' into '%s'" ), track->m_FileName.c_str(), TmpFile.c_str() );
wxRemoveFile( TmpFile );
return wxNOT_FOUND;
}
}
//if( !CoverPath.IsEmpty() )
if( m_PortableDevice->CoverFormats() & guPORTABLEMEDIA_COVER_FORMAT_EMBEDDED )
{
guTagSetPicture( TmpFile, CoverPath );
}
if( !itdb_cp_track_to_ipod( iPodTrack, TmpFile.mb_str( wxConvFile ), NULL ) )
{
guLogMessage( wxT( "Error trying to copy the file '%s'" ), TmpFile.c_str() );
wxRemoveFile( TmpFile );
return wxNOT_FOUND;
}
wxRemoveFile( TmpFile );
filename = wxString( iPodTrack->ipod_path, wxConvUTF8 );
return iPodTrack->size;
}
// -------------------------------------------------------------------------------- //
void guMediaVieweriPodDevice::UpdateTracks( const guTrackArray &tracks, const guImagePtrArray &images,
const wxArrayString &lyrics, const wxArrayInt &changedflags )
{
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
guTrack &Track = tracks[ Index ];
Itdb_Track * iPodTrack = ( ( guIpodLibrary * ) m_Db )->iPodFindTrack( Track.m_FileName );
if( iPodTrack )
{
CheckUpdateField( &iPodTrack->title, Track.m_SongName );
CheckUpdateField( &iPodTrack->album, Track.m_AlbumName );
CheckUpdateField( &iPodTrack->artist, Track.m_ArtistName );
CheckUpdateField( &iPodTrack->genre, Track.m_GenreName );
CheckUpdateField( &iPodTrack->comment, Track.m_Comments );
CheckUpdateField( &iPodTrack->composer, Track.m_Composer );
CheckUpdateField( &iPodTrack->albumartist, Track.m_AlbumArtist );
iPodTrack->size = Track.m_FileSize;
iPodTrack->tracklen = Track.m_Length;
iPodTrack->track_nr = Track.m_Number;
guStrDiskToDiskNum( Track.m_Disk, iPodTrack->cd_nr, iPodTrack->cds );
iPodTrack->bitrate = Track.m_Bitrate;
iPodTrack->year = Track.m_Year;
iPodTrack->BPM = 0;
iPodTrack->rating = ( Track.m_Rating == wxNOT_FOUND ) ? 0 : Track.m_Rating * ITDB_RATING_STEP;
iPodTrack->type2 = Track.m_Format == wxT( "mp3" ) ? 1 : 0;
}
}
( ( guIpodLibrary * ) m_Db )->iPodFlush();
guMediaViewer::UpdateTracks( tracks, images, lyrics, changedflags );
}
// -------------------------------------------------------------------------------- //
wxImage * guMediaVieweriPodDevice::GetAlbumCover( const int albumid, int &coverid, wxString &coverpath,
const wxString &artistname, const wxString &albumname )
{
Itdb_iTunesDB * iPodDb = ( ( guIpodLibrary * ) m_Db )->GetiPodDb();
if( iPodDb )
{
wxString SongPath;
wxSQLite3ResultSet dbRes;
wxString query;
if( albumid )
{
query = wxString::Format( wxT( "SELECT song_path, song_filename FROM songs WHERE song_albumid = %i LIMIT 1;" ), albumid );
}
else if( coverid )
{
query = wxString::Format( wxT( "SELECT song_path, song_filename FROM songs WHERE song_coverid = %i LIMIT 1;" ), coverid );
}
if( !query.IsEmpty() )
{
dbRes = m_Db->ExecuteQuery( query );
if( dbRes.NextRow() )
{
SongPath = dbRes.GetString( 0 ) + dbRes.GetString( 1 );
}
dbRes.Finalize();
if( !SongPath.IsEmpty() )
{
Itdb_Track * iPodTrack = ( ( guIpodLibrary * ) m_Db )->iPodFindTrack( SongPath );
if( iPodTrack )
{
GdkPixbuf * Pixbuf = ( GdkPixbuf * ) itdb_track_get_thumbnail( iPodTrack, -1, -1 );
if( Pixbuf )
{
void * Buffer = NULL;
gsize BufferSize = 0;
if( gdk_pixbuf_save_to_buffer( Pixbuf, ( gchar ** ) &Buffer, &BufferSize, "jpeg", NULL, "quality", "100", NULL ) )
{
wxMemoryInputStream ImageStream( Buffer, BufferSize );
wxImage * CoverImage = new wxImage( ImageStream, wxBITMAP_TYPE_JPEG );
if( CoverImage )
{
if( CoverImage->IsOk() )
{
return CoverImage;
}
else
{
delete CoverImage;
guLogMessage( wxT( "Error in image from ipod..." ) );
}
}
g_free( Buffer );
}
else
{
guLogMessage( wxT( "Couldnt save to a buffer the pixbuf for cover %i" ), coverid );
}
g_object_unref( Pixbuf );
}
else
{
guLogMessage( wxT( "Couldnt get the pixbuf for cover %i" ), coverid );
}
}
}
}
}
return NULL;
}
}
#endif
// -------------------------------------------------------------------------------- //
| 78,534
|
C++
|
.cpp
| 1,642
| 33.128502
| 173
| 0.492435
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,614
|
AlListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/AlListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AlListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "OnlineLinks.h"
#include "Utils.h"
#include "Settings.h"
#include "LibPanel.h"
#include <wx/renderer.h>
#define ALLISTBOX_ITEM_SIZE 40
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
// guAlListBox
// -------------------------------------------------------------------------------- //
guAlListBox::guAlListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guListView( parent, wxLB_MULTIPLE | guLISTVIEW_ALLOWDRAG | guLISTVIEW_HIDE_HEADER )
{
m_Db = db;
m_Items = new guAlbumItems();
m_LibPanel = libpanel;
m_SysFontPointSize = wxSystemSettings::GetFont( wxSYS_SYSTEM_FONT ).GetPointSize();
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_ConfigPath = libpanel->GetMediaViewer()->ConfigPath();
m_AlbumsOrder = Config->ReadNum( wxT( "AlbumsOrder" ), 0, m_ConfigPath );
m_Db->SetAlbumsOrder( m_AlbumsOrder );
guListViewColumn * Column = new guListViewColumn( label, 0 );
InsertColumn( Column );
Bind( wxEVT_MENU, &guAlListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guAlListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Bind( wxEVT_MENU, &guAlListBox::OnOrderSelected, this, ID_ALBUM_ORDER_NAME, ID_ALBUM_ORDER_ARTIST_YEAR_REVERSE );
Bind( guConfigUpdatedEvent, &guAlListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guAlListBox::~guAlListBox()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteNum( wxT( "AlbumsOrder" ), m_AlbumsOrder, m_ConfigPath );
if( m_Items )
delete m_Items;
Unbind( wxEVT_MENU, &guAlListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAlListBox::OnOrderSelected, this, ID_ALBUM_ORDER_NAME, ID_ALBUM_ORDER_ARTIST_YEAR_REVERSE );
Unbind( guConfigUpdatedEvent, &guAlListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guAlListBox::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guAlListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_ALBUM_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_ALBUM_EDITLABELS );
RealAccelCmds.Add( ID_ALBUM_EDITTRACKS );
RealAccelCmds.Add( ID_ALBUM_PLAY );
RealAccelCmds.Add( ID_ALBUM_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_ALBUM_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_ALBUM_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_ALBUM_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
bool guAlListBox::SelectAlbumName( const wxString &AlbumName )
{
long item = FindItem( 0, AlbumName, false );
if( item != wxNOT_FOUND )
{
wxArrayInt * Albums = new wxArrayInt();
Albums->Add( ( * m_Items )[ item ].m_Id );
wxCommandEvent event( wxEVT_MENU, ID_ALBUM_SETSELECTION );
event.SetClientData( ( void * ) Albums );
wxPostEvent( guMainFrame::GetMainFrame(), event );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
void guAlListBox::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
m_Attr.m_Font->SetPointSize( m_SysFontPointSize );
guAlbumItem * Item = &( * ( guAlbumItems * ) m_Items )[ row ];
dc.SetFont( * m_Attr.m_Font );
dc.SetBackgroundMode( wxTRANSPARENT );
dc.SetTextForeground( IsSelected( row ) ? m_Attr.m_SelFgColor : m_Attr.m_TextFgColor );
dc.DrawText( Item->m_Name, rect.x + 45, rect.y + 4 );
if( Item->m_Year )
{
int Pos;
dc.GetTextExtent( Item->m_Name, &Pos, NULL );
Pos += rect.x + 45;
m_Attr.m_Font->SetPointSize( m_SysFontPointSize - 3 );
dc.SetFont( * m_Attr.m_Font );
dc.DrawText( wxString::Format( wxT( " (%4u)" ), Item->m_Year ), Pos, rect.y + 7 );
}
if( !Item->m_ArtistName.IsEmpty() )
{
m_Attr.m_Font->SetPointSize( m_SysFontPointSize - 2 );
dc.SetFont( * m_Attr.m_Font );
dc.DrawText( _( "by " ) + Item->m_ArtistName, rect.x + 45, rect.y + 22 );
}
if( Item->m_Thumb )
{
dc.DrawBitmap( * Item->m_Thumb, rect.x + 1, rect.y + 1, false );
}
// else if( Item->m_Thumb )
// {
// guLogError( wxT( "Thumb image corrupt or not correctly loaded" ) );
// }
}
// -------------------------------------------------------------------------------- //
void guAlListBox::OnOrderSelected( wxCommandEvent &event )
{
m_AlbumsOrder = event.GetId() - ID_ALBUM_ORDER_NAME;
m_Db->SetAlbumsOrder( m_AlbumsOrder );
ReloadItems( false );
}
// -------------------------------------------------------------------------------- //
wxCoord guAlListBox::OnMeasureItem( size_t n ) const
{
// Code taken from the generic/listctrl.cpp file
guAlListBox * self = wxConstCast( this, guAlListBox );
self->SetItemHeight( ALLISTBOX_ITEM_SIZE );
return wxCoord( ALLISTBOX_ITEM_SIZE );
}
// -------------------------------------------------------------------------------- //
int guAlListBox::GetSelectedSongs( guTrackArray * tracks, const bool isdrag ) const
{
int Count = m_Db->GetAlbumsSongs( GetSelectedItems(), tracks );
m_LibPanel->NormalizeTracks( tracks, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void AddAlbumCommands( wxMenu * Menu, int SelCount )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem;
if( Menu )
{
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( Commands[ index ].Find( guCOMMAND_COVERPATH ) == wxNOT_FOUND ) || ( SelCount == 1 ) )
{
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
SubMenu->Append( MenuItem );
}
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guAlListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
int SelCount = GetSelectedCount();
if( SelCount )
{
MenuItem = new wxMenuItem( Menu, ID_ALBUM_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected albums" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ALBUM_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected albums to the Playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUM_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUM_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUM_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu, _( "Add the selected albums after" ) );
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ALBUM_EDITLABELS,
wxString( _( "Edit Labels" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITLABELS ),
_( "Edit the labels assigned to the selected albums" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( Menu, ID_ALBUM_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
}
wxMenu * SubMenu = new wxMenu();
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_NAME, _( "Name" ), _( "Albums are sorted by name" ) );
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_YEAR, _( "Year" ), _( "Albums are sorted by year" ) );
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_YEAR_REVERSE, _( "Year Descending" ), _( "Albums are sorted by year descending" ) );
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_ARTIST_NAME, _( "Artist, Name" ), _( "Albums are sorted by artist and album name" ) );
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_ARTIST_YEAR, _( "Artist, Year" ), _( "Albums are sorted by artist and year" ) );
SubMenu->AppendRadioItem( ID_ALBUM_ORDER_ARTIST_YEAR_REVERSE, _( "Artist, Year Descending" ), _( "Albums are sorted by artist and year descending" ) );
MenuItem = SubMenu->FindItemByPosition( m_Db->GetAlbumsOrder() );
MenuItem->Check( true );
Menu->Append( wxID_ANY, _( "Sort By" ), SubMenu, _( "Sets the albums order" ) );
if( SelCount )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ALBUM_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to Playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ALBUM_CREATE_BESTOF_PLAYLIST,
wxString( _( "Create Best of Playlist" ) ),
_( "Create a playlist with the best of this artist" ) );
Menu->Append( MenuItem );
if( SelCount == 1 && ( ContextMenuFlags & guCONTEXTMENU_DOWNLOAD_COVERS ) )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ALBUM_MANUALCOVER, _( "Download Cover" ), _( "Download cover for the current selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ALBUM_SELECT_COVER, _( "Select Cover" ), _( "Select the cover image file from disk" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_download_covers ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ALBUM_COVER_DELETE, _( "Delete Cover" ), _( "Delete the cover for the selected album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
}
if( ContextMenuFlags & guCONTEXTMENU_EMBED_COVERS )
{
MenuItem = new wxMenuItem( Menu, ID_ALBUM_COVER_EMBED, _( "Embed Cover" ), _( "Embed the current cover to the album files" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
}
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu->AppendSeparator();
if( ( m_LibPanel->GetContextMenuFlags() & guCONTEXTMENU_COPY_TO ) )
{
m_LibPanel->CreateCopyToMenu( Menu );
}
if( SelCount == 1 && ( ContextMenuFlags & guCONTEXTMENU_LINKS ) )
{
AddOnlineLinksMenu( Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
AddAlbumCommands( Menu, SelCount );
}
}
m_LibPanel->CreateContextMenu( Menu, guLIBRARY_ELEMENT_ALBUMS );
}
// -------------------------------------------------------------------------------- //
void guAlListBox::OnSearchLinkClicked( wxCommandEvent &event )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
if( Item != wxNOT_FOUND )
{
ExecuteOnlineLink( event.GetId(), GetSearchText( Item ) );
}
}
// -------------------------------------------------------------------------------- //
void guAlListBox::OnCommandClicked( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
//guLogMessage( wxT( "CommandId: %u" ), index );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayString AlbumPaths = m_Db->GetAlbumsPaths( Selection );
wxString Paths = wxEmptyString;
int count = AlbumPaths.Count();
for( int index = 0; index < count; index++ )
{
//Paths += wxT( " \"" ) + AlbumPaths[ index ] + wxT( "\"" );
AlbumPaths[ index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
int CoverId = m_Db->GetAlbumCoverId( Selection[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
wxString SongList = wxEmptyString;
if( m_Db->GetAlbumsSongs( Selection, &Songs ) )
{
int count = Songs.Count();
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + Songs[ index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
wxString guAlListBox::GetSearchText( int item ) const
{
return wxString::Format( wxT( "\"%s\" \"%s\"" ),
m_Db->GetArtistName( ( * m_Items )[ item ].m_ArtistId ).c_str(),
( * m_Items )[ item ].m_Name.c_str() );
}
// -------------------------------------------------------------------------------- //
void guAlListBox::ReloadItems( bool reset )
{
wxArrayInt Selection;
int FirstVisible = GetVisibleRowsBegin();
if( reset )
SetSelection( -1 );
else
Selection = GetSelectedItems( false );
m_Items->Empty();
GetItemsList();
m_Items->Insert( new guAlbumItem( 0, wxString::Format( wxT( "%s (%lu)" ), _( "All" ), m_Items->Count() ) ), 0 );
SetItemCount( m_Items->Count() );
if( !reset )
{
SetSelectedItems( Selection );
ScrollToRow( FirstVisible );
}
RefreshAll();
}
//// -------------------------------------------------------------------------------- //
//void guAlListBox::SetSelectedItems( const wxArrayInt &selection )
//{
// guListView::SetSelectedItems( selection );
//
//// wxCommandEvent event( wxEVT_LISTBOX, GetId() );
//// event.SetEventObject( this );
//// event.SetInt( -1 );
//// (void) GetEventHandler()->ProcessEvent( event );
//}
// -------------------------------------------------------------------------------- //
int guAlListBox::FindAlbum( const int albumid )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Id == albumid )
{
return Index;
}
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 21,020
|
C++
|
.cpp
| 441
| 39.664399
| 155
| 0.560267
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,615
|
TaListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/TaListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "TaListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "Utils.h"
#include "LibPanel.h"
#include "MediaViewer.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guTaListBox::guTaListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
Bind( wxEVT_MENU, &guTaListBox::AddLabel, this, ID_LABEL_ADD );
Bind( wxEVT_MENU, &guTaListBox::DelLabel, this, ID_LABEL_DELETE );
Bind( wxEVT_MENU, &guTaListBox::EditLabel, this, ID_LABEL_EDIT );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guTaListBox::~guTaListBox()
{
Unbind( wxEVT_MENU, &guTaListBox::AddLabel, this, ID_LABEL_ADD );
Unbind( wxEVT_MENU, &guTaListBox::DelLabel, this, ID_LABEL_DELETE );
Unbind( wxEVT_MENU, &guTaListBox::EditLabel, this, ID_LABEL_EDIT );
}
// -------------------------------------------------------------------------------- //
void guTaListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_LABEL_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_LABEL_PLAY );
RealAccelCmds.Add( ID_LABEL_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_LABEL_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_LABEL_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_LABEL_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guTaListBox::GetItemsList( void )
{
m_Db->GetLabels( m_Items );
}
// -------------------------------------------------------------------------------- //
int guTaListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetLabelsSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guTaListBox::CreateContextMenu( wxMenu * Menu ) const
{
int SelCount = GetSelectedCount();
wxMenuItem * MenuItem;
MenuItem = new wxMenuItem( Menu, ID_LABEL_ADD, _( "Create" ), _( "Create a new label" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu->Append( MenuItem );
if( SelCount )
{
MenuItem = new wxMenuItem( Menu, ID_LABEL_EDIT, _( "Rename" ), _( "Change selected label" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_LABEL_DELETE, _( "Delete" ), _( "Delete selected labels" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_LABEL_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected labels" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_LABEL_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected labels to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_LABEL_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_LABEL_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_LABEL_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_LABEL_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( m_LibPanel->GetContextMenuFlags() & guCONTEXTMENU_COPY_TO )
{
Menu->AppendSeparator();
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
void guTaListBox::AddLabel( wxCommandEvent &event )
{
//wxMessageBox( wxT( "AddLabel" ), wxT( "Information" ) );
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Label Name: " ), _( "Please enter the label name" ) );
if( EntryDialog->ShowModal() == wxID_OK )
{
//wxMessageBox( EntryDialog->GetValue(), wxT( "Entered..." ) );
m_Db->AddLabel( EntryDialog->GetValue() );
ReloadItems();
}
EntryDialog->Destroy();
}
// -------------------------------------------------------------------------------- //
void guTaListBox::DelLabel( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
int Count = Selection.Count();
if( Count )
{
if( wxMessageBox( _( "Are you sure to delete the selected labels?" ),
_( "Confirm" ),
wxICON_QUESTION|wxYES_NO|wxNO_DEFAULT, this ) == wxYES )
{
for( int Index = 0; Index < Count; Index++ )
{
m_Db->DelLabel( Selection[ Index ] );
}
ReloadItems();
}
}
}
// -------------------------------------------------------------------------------- //
void guTaListBox::EditLabel( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
if( Selection.Count() )
{
// Get the Index of the First Selected Item
if( Selection[ 0 ] )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
wxTextEntryDialog * EntryDialog = new wxTextEntryDialog( this, _( "Label Name: " ),
_( "Enter the new label name" ), ( * m_Items )[ Item ] .m_Name );
if( EntryDialog->ShowModal() == wxID_OK &&
( * m_Items )[ Item ].m_Name != EntryDialog->GetValue() )
{
m_Db->SetLabelName( Selection[ 0 ], ( * m_Items )[ Item ].m_Name, EntryDialog->GetValue() );
ReloadItems();
}
EntryDialog->Destroy();
}
}
}
}
// -------------------------------------------------------------------------------- //
| 9,697
|
C++
|
.cpp
| 208
| 39.692308
| 130
| 0.568497
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,616
|
ArListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/ArListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ArListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "LibPanel.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "MediaViewer.h"
#include "OnlineLinks.h"
#include "Settings.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guArListBox::guArListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
Bind( wxEVT_MENU, &guArListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guArListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
CreateAcceleratorTable();
ReloadItems();
};
// -------------------------------------------------------------------------------- //
guArListBox::~guArListBox()
{
Unbind( wxEVT_MENU, &guArListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guArListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
}
// -------------------------------------------------------------------------------- //
void guArListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_ARTIST_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_ARTIST_EDITLABELS );
RealAccelCmds.Add( ID_ARTIST_EDITTRACKS );
RealAccelCmds.Add( ID_ARTIST_PLAY );
RealAccelCmds.Add( ID_ARTIST_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_ARTIST_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_ARTIST_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_ARTIST_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guArListBox::GetItemsList( void )
{
m_Db->GetArtists( m_Items );
}
// -------------------------------------------------------------------------------- //
int guArListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetArtistsSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void AddArtistCommands( wxMenu * Menu, int SelCount )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem;
if( Menu )
{
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( Commands[ index ].Find( guCOMMAND_COVERPATH ) == wxNOT_FOUND ) || ( SelCount == 1 ) )
{
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
SubMenu->Append( MenuItem );
}
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guArListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_ARTIST_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected artists" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_ARTIST_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected artists to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ARTIST_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ARTIST_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ARTIST_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ARTIST_EDITLABELS,
wxString( _( "Edit Labels" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITLABELS ),
_( "Edit the labels assigned to the selected artists" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( Menu, ID_ARTIST_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the songs from the selected artists" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ARTIST_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ARTIST_CREATE_BESTOF_PLAYLIST,
wxString( _( "Create Best of Playlist" ) ),
_( "Create a playlist with the best of this aretist" ) );
Menu->Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu->AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
m_LibPanel->CreateCopyToMenu( Menu );
}
if( SelCount == 1 && ( ContextMenuFlags & guCONTEXTMENU_LINKS ) )
{
AddOnlineLinksMenu( Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
AddArtistCommands( Menu, SelCount );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
void guArListBox::OnSearchLinkClicked( wxCommandEvent &event )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
if( Item != wxNOT_FOUND )
{
ExecuteOnlineLink( event.GetId(), GetSearchText( Item ) );
}
}
// -------------------------------------------------------------------------------- //
void guArListBox::OnCommandClicked( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
//guLogMessage( wxT( "CommandId: %u" ), index );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayInt AlbumList;
m_Db->GetArtistsAlbums( Selection, &AlbumList );
wxArrayString AlbumPaths = m_Db->GetAlbumsPaths( AlbumList );
wxString Paths = wxEmptyString;
int count = AlbumPaths.Count();
for( int index = 0; index < count; index++ )
{
AlbumPaths[ index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
wxArrayInt AlbumList;
m_Db->GetArtistsAlbums( Selection, &AlbumList );
int CoverId = m_Db->GetAlbumCoverId( AlbumList[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
wxString SongList = wxEmptyString;
if( m_Db->GetArtistsSongs( Selection, &Songs ) )
{
int count = Songs.Count();
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + Songs[ index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
wxString guArListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
// -------------------------------------------------------------------------------- //
bool guArListBox::SelectArtistName( const wxString &ArtistName )
{
int item = FindItem( 0, ArtistName, false );
if( item != wxNOT_FOUND )
{
wxArrayInt * Artists = new wxArrayInt();
Artists->Add( ( * m_Items )[ item ].m_Id );
wxCommandEvent event( wxEVT_MENU, ID_ARTIST_SETSELECTION );
event.SetClientData( ( void * ) Artists );
wxPostEvent( guMainFrame::GetMainFrame(), event );
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
int guArListBox::FindArtist( const int artistid )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Id == artistid )
{
return Index;
}
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 14,267
|
C++
|
.cpp
| 309
| 37.537217
| 132
| 0.555292
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,617
|
EditWithOptions.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/EditWithOptions.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "EditWithOptions.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guEditWithOptions::guEditWithOptions( wxWindow * parent, const wxString &title, const wxString &label, const wxString &defval, const wxArrayString &items ) :
wxDialog( parent, wxID_ANY, title, wxDefaultPosition, wxSize( 370, 175 ), wxDEFAULT_DIALOG_STYLE )
{
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainFrame;
MainFrame = new wxBoxSizer( wxVERTICAL );
wxBoxSizer * TopFrame;
TopFrame = new wxBoxSizer( wxHORIZONTAL );
wxStaticText * EditLabel = new wxStaticText( this, wxID_ANY, label + wxT( ":" ), wxDefaultPosition, wxDefaultSize, 0 );
EditLabel->Wrap( -1 );
TopFrame->Add( EditLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_EditComboBox = new wxComboBox( this, wxID_ANY, defval, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
m_EditComboBox->Append( items );
TopFrame->Add( m_EditComboBox, 1, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );
MainFrame->Add( TopFrame, 1, wxEXPAND, 5 );
wxStdDialogButtonSizer * ButtonFrame = new wxStdDialogButtonSizer();
wxButton * ButtonOK = new wxButton( this, wxID_OK );
ButtonFrame->AddButton( ButtonOK );
wxButton * ButtonCancel = new wxButton( this, wxID_CANCEL );
ButtonFrame->AddButton( ButtonCancel );
ButtonFrame->SetAffirmativeButton( ButtonOK );
ButtonFrame->SetCancelButton( ButtonCancel );
ButtonFrame->Realize();
MainFrame->Add( ButtonFrame, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
SetSizer( MainFrame );
Layout();
ButtonOK->SetDefault();
// SetEscapeId( wxID_CANCEL );
m_EditComboBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guEditWithOptions::~guEditWithOptions()
{
}
// -------------------------------------------------------------------------------- //
wxString guEditWithOptions::GetData( void )
{
int Selected = m_EditComboBox->GetCurrentSelection();
if( Selected != wxNOT_FOUND )
return m_EditComboBox->GetString( Selected );
return m_EditComboBox->GetValue();
}
}
// -------------------------------------------------------------------------------- //
| 3,324
|
C++
|
.cpp
| 68
| 45.808824
| 157
| 0.609139
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,618
|
RaListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/RaListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "RaListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "OnlineLinks.h"
#include "RatingCtrl.h"
#include "MainApp.h"
#include "MediaViewer.h"
#include "Utils.h"
#include "LibPanel.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guRaListBox::guRaListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
m_NormalStar = new wxBitmap( guImage( ( guIMAGE_INDEX ) ( guIMAGE_INDEX_star_normal_tiny + GURATING_STYLE_MID ) ) );
m_SelectStar = new wxBitmap( guImage( ( guIMAGE_INDEX ) ( guIMAGE_INDEX_star_highlight_tiny + GURATING_STYLE_MID ) ) );
CreateAcceleratorTable();
ReloadItems();
};
// -------------------------------------------------------------------------------- //
guRaListBox::~guRaListBox()
{
if( m_NormalStar )
delete m_NormalStar;
if( m_SelectStar )
delete m_SelectStar;
}
// -------------------------------------------------------------------------------- //
void guRaListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_RATING_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_RATING_EDITTRACKS );
RealAccelCmds.Add( ID_RATING_PLAY );
RealAccelCmds.Add( ID_RATING_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_RATING_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_RATING_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_RATING_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guRaListBox::GetItemsList( void )
{
m_Db->GetRatings( m_Items );
}
// -------------------------------------------------------------------------------- //
int guRaListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
wxArrayInt Items = GetSelectedItems();
int Count = Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Items[ Index ] )
Items[ Index ]--;
}
Count = m_Db->GetRatingsSongs( Items, songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guRaListBox::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
if( row == 0 )
{
guListBox::DrawItem( dc, rect, row, col );
}
else
{
int Rating = GetItemId( row ) - 1;
dc.SetBackgroundMode( wxTRANSPARENT );
int x;
int w = ( ( GURATING_STYLE_MID * 2 ) + GURATING_IMAGE_SIZE );
for( x = 0; x < 5; x++ )
{
dc.DrawBitmap( ( x >= Rating ) ? * m_NormalStar : * m_SelectStar,
rect.x + 3 + ( w * x ), rect.y + 3, true );
}
}
}
// -------------------------------------------------------------------------------- //
void guRaListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_RATING_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_RATING_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_RATING_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_RATING_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_RATING_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_RATING_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_RATING_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
Menu->AppendSeparator();
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
wxString guRaListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
}
// -------------------------------------------------------------------------------- //
| 8,537
|
C++
|
.cpp
| 187
| 39.048128
| 130
| 0.574796
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,619
|
CoListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/CoListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "CoListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "OnlineLinks.h"
#include "MainApp.h"
#include "MediaViewer.h"
#include "Utils.h"
#include "LibPanel.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guCoListBox::guCoListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guCoListBox::~guCoListBox()
{
}
// -------------------------------------------------------------------------------- //
void guCoListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_COMPOSER_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_COMPOSER_EDITTRACKS );
RealAccelCmds.Add( ID_COMPOSER_PLAY );
RealAccelCmds.Add( ID_COMPOSER_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_COMPOSER_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_COMPOSER_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_COMPOSER_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guCoListBox::GetItemsList( void )
{
m_Db->GetComposers( m_Items );
}
// -------------------------------------------------------------------------------- //
int guCoListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetComposersSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guCoListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_COMPOSER_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected composer" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_COMPOSER_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_COMPOSER_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_COMPOSER_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_COMPOSER_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected albums to the Playlist as Next Tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu, _( "Add the selected albums after" ) );
if( SelCount )
{
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_COMPOSER_EDITTRACKS,
wxString( _( "Edit songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_COMPOSER_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
Menu->AppendSeparator();
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
wxString guCoListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
// -------------------------------------------------------------------------------- //
int guCoListBox::FindComposer( const wxString &composer )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Name == composer )
{
return Index;
}
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 7,755
|
C++
|
.cpp
| 166
| 40.216867
| 132
| 0.578669
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,620
|
AAListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/AAListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AAListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "LibPanel.h"
#include "OnlineLinks.h"
#include "MainApp.h"
#include "MediaViewer.h"
#include "Settings.h"
#include "Utils.h"
using namespace Guayadeque;
// -------------------------------------------------------------------------------- //
guAAListBox::guAAListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
Bind( wxEVT_MENU, &guAAListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guAAListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guAAListBox::~guAAListBox()
{
Unbind( wxEVT_MENU, &guAAListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guAAListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
}
// -------------------------------------------------------------------------------- //
void guAAListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_ALBUMARTIST_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_ALBUMARTIST_EDITTRACKS );
RealAccelCmds.Add( ID_ALBUMARTIST_PLAY );
RealAccelCmds.Add( ID_ALBUMARTIST_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_ALBUMARTIST_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_ALBUMARTIST_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_ALBUMARTIST_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guAAListBox::GetItemsList( void )
{
m_Db->GetAlbumArtists( m_Items );
}
// -------------------------------------------------------------------------------- //
int guAAListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetAlbumArtistsSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void AddAlbumArtistCommands( wxMenu * Menu, int SelCount )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem;
if( Menu )
{
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( Commands[ index ].Find( guCOMMAND_COVERPATH ) == wxNOT_FOUND ) || ( SelCount == 1 ) )
{
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
SubMenu->Append( MenuItem );
}
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guAAListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_ALBUMARTIST_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected album artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_ALBUMARTIST_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMARTIST_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMARTIST_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_ALBUMARTIST_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ALBUMARTIST_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_ALBUMARTIST_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to Playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_ALBUMARTIST_CREATE_BESTOF_PLAYLIST,
wxString( _( "Create Best of Playlist" ) ),
_( "Create a playlist with the best of this artist" ) );
Menu->Append( MenuItem );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu->AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
m_LibPanel->CreateCopyToMenu( Menu );
}
if( SelCount == 1 && ( ContextMenuFlags & guCONTEXTMENU_LINKS ) )
{
AddOnlineLinksMenu( Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
AddAlbumArtistCommands( Menu, SelCount );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
wxString guAAListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
// -------------------------------------------------------------------------------- //
int guAAListBox::FindAlbumArtist( const wxString &albumartist )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Name == albumartist )
{
return Index;
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guAAListBox::OnSearchLinkClicked( wxCommandEvent &event )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
if( Item != wxNOT_FOUND )
{
ExecuteOnlineLink( event.GetId(), GetSearchText( Item ) );
}
}
// -------------------------------------------------------------------------------- //
void guAAListBox::OnCommandClicked( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
//guLogMessage( wxT( "CommandId: %u" ), index );
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
wxArrayInt AlbumList;
m_Db->GetAlbumArtistsAlbums( Selection, &AlbumList );
wxArrayString AlbumPaths = m_Db->GetAlbumsPaths( AlbumList );
wxString Paths = wxEmptyString;
int count = AlbumPaths.Count();
for( int index = 0; index < count; index++ )
{
AlbumPaths[ index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
wxArrayInt AlbumList;
m_Db->GetAlbumArtistsAlbums( Selection, &AlbumList );
int CoverId = m_Db->GetAlbumCoverId( AlbumList[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
wxString SongList = wxEmptyString;
if( m_Db->GetAlbumArtistsSongs( Selection, &Songs ) )
{
int count = Songs.Count();
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + Songs[ index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
| 13,345
|
C++
|
.cpp
| 285
| 38.014035
| 132
| 0.556665
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,621
|
GeListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/GeListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "GeListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "Utils.h"
#include "LibPanel.h"
#include "MediaViewer.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guGeListBox::guGeListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guGeListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_GENRE_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_GENRE_PLAY );
RealAccelCmds.Add( ID_GENRE_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_GENRE_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_GENRE_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_GENRE_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guGeListBox::GetItemsList( void )
{
m_Db->GetGenres( m_Items );
}
// -------------------------------------------------------------------------------- //
int guGeListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetGenresSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guGeListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
MenuItem = new wxMenuItem( Menu, ID_GENRE_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected genres" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_GENRE_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected genres to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_GENRE_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_GENRE_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_GENRE_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_GENRE_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_doc_save ) );
Menu->Append( MenuItem );
if( m_LibPanel->GetContextMenuFlags() & guCONTEXTMENU_COPY_TO )
{
Menu->AppendSeparator();
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
}
// -------------------------------------------------------------------------------- //
| 6,281
|
C++
|
.cpp
| 130
| 42.253846
| 130
| 0.598433
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,622
|
YeListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/YeListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "YeListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "OnlineLinks.h"
#include "MainApp.h"
#include "Utils.h"
#include "LibPanel.h"
#include "MediaViewer.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guYeListBox::guYeListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
CreateAcceleratorTable();
ReloadItems();
};
// -------------------------------------------------------------------------------- //
guYeListBox::~guYeListBox()
{
}
// -------------------------------------------------------------------------------- //
void guYeListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_YEAR_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_YEAR_EDITTRACKS );
RealAccelCmds.Add( ID_YEAR_PLAY );
RealAccelCmds.Add( ID_YEAR_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_YEAR_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_YEAR_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_YEAR_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guYeListBox::GetItemsList( void )
{
m_Db->GetYears( m_Items );
}
// -------------------------------------------------------------------------------- //
int guYeListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
int Count = m_Db->GetYearsSongs( GetSelectedItems(), songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guYeListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_YEAR_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected artists" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_YEAR_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_YEAR_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_YEAR_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_YEAR_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_YEAR_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_YEAR_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to Playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
wxString guYeListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
// -------------------------------------------------------------------------------- //
int guYeListBox::FindYear( const int year )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Id == year )
{
return Index;
}
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 7,604
|
C++
|
.cpp
| 165
| 39.678788
| 130
| 0.575189
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,623
|
PcListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/PcListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "PcListBox.h"
#include "Accelerators.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "OnlineLinks.h"
#include "MainApp.h"
#include "Utils.h"
#include "LibPanel.h"
#include "MediaViewer.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guPcListBox::guPcListBox( wxWindow * parent, guLibPanel * libpanel, guDbLibrary * db, const wxString &label ) :
guAccelListBox( parent, db, label )
{
m_LibPanel = libpanel;
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guPcListBox::~guPcListBox()
{
}
// -------------------------------------------------------------------------------- //
void guPcListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_PLAY );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_PLAYCOUNT_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_PLAYCOUNT_EDITTRACKS );
RealAccelCmds.Add( ID_PLAYCOUNT_PLAY );
RealAccelCmds.Add( ID_PLAYCOUNT_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_PLAYCOUNT_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_PLAYCOUNT_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_PLAYCOUNT_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
void guPcListBox::GetItemsList( void )
{
m_Db->GetPlayCounts( m_Items );
}
// -------------------------------------------------------------------------------- //
int guPcListBox::GetSelectedSongs( guTrackArray * songs, const bool isdrag ) const
{
wxArrayInt Items = GetSelectedItems();
int Count = Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( Items[ Index ] )
Items[ Index ]--;
}
Count = m_Db->GetPlayCountsSongs( Items, songs );
m_LibPanel->NormalizeTracks( songs, isdrag );
return Count;
}
// -------------------------------------------------------------------------------- //
void guPcListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_LibPanel->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_PLAYCOUNT_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_PLAYCOUNT_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYCOUNT_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYCOUNT_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_PLAYCOUNT_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_PLAYCOUNT_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_PLAYCOUNT_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save the selected tracks to playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
Menu->AppendSeparator();
m_LibPanel->CreateCopyToMenu( Menu );
}
}
m_LibPanel->CreateContextMenu( Menu );
}
// -------------------------------------------------------------------------------- //
wxString guPcListBox::GetSearchText( int item ) const
{
return GetItemName( item );
}
}
// -------------------------------------------------------------------------------- //
| 7,545
|
C++
|
.cpp
| 160
| 40.6125
| 130
| 0.586268
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,624
|
LibPanel.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/LibPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "LibPanel.h"
#include "AuiDockArt.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "CoverEdit.h"
#include "EditWithOptions.h"
#include "Images.h"
#include "LabelEditor.h"
#include "MainFrame.h"
#include "PlayListAppend.h"
#include "SelCoverFile.h"
#include "TagInfo.h"
#include "TrackEdit.h"
#include "Utils.h"
#include <wx/event.h>
#include <wx/uri.h>
namespace Guayadeque {
#define LISTCTRL_BORDER 5
#define guPANEL_TIMER_SELECTION 1
#define guPANEL_TIMER_TEXTSEARCH 2
#define guPANEL_TIMER_SELCHANGED 50
#define guPANEL_TIMER_TEXTCHANGED 500
// -------------------------------------------------------------------------------- //
guLibPanel::guLibPanel( wxWindow * parent, guMediaViewer * mediaviewer ) :
guAuiManagerPanel( parent ),
m_SelChangedTimer( this, guPANEL_TIMER_SELECTION )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_PlayerPanel = mediaviewer->GetPlayerPanel();
m_ConfigPath = mediaviewer->ConfigPath() + wxT( "/library" );
m_UpdateLock = false;
m_VisiblePanels = Config->ReadNum( wxT( "VisiblePanels" ), guPANEL_LIBRARY_VISIBLE_DEFAULT, m_ConfigPath );
CreateControls();
//
LoadLastLayout();
}
// -------------------------------------------------------------------------------- //
guLibPanel::~guLibPanel()
{
// Save the Splitter positions into the main config
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->WriteNum( wxT( "VisiblePanels" ), m_VisiblePanels, m_ConfigPath );
Config->WriteStr( wxT( "Layout" ), m_AuiManager.SavePerspective(), m_ConfigPath );
Unbind( wxEVT_TIMER, &guLibPanel::OnSelChangedTimer, this, guPANEL_TIMER_SELECTION );
//
m_GenreListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnGenreListSelected, this );
m_GenreListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnGenreListActivated, this );
m_LabelsListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnLabelListSelected, this );
m_LabelsListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnLabelListActivated, this );
m_ArtistListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnArtistListSelected, this );
m_ArtistListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnArtistListActivated, this );
m_AlbumListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnAlbumListSelected, this );
m_AlbumListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnAlbumListActivated, this );
m_YearListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnYearListSelected, this );
m_YearListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnYearListActivated, this );
m_RatingListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnRatingListSelected, this );
m_RatingListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnRatingListActivated, this );
m_PlayCountListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnPlayCountListSelected, this );
m_PlayCountListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnPlayCountListActivated, this );
m_ComposerListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnComposerListSelected, this );
m_ComposerListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnComposerListActivated, this );
m_AlbumArtistListCtrl->Unbind( wxEVT_LISTBOX, &guLibPanel::OnAlbumArtistListSelected, this );
m_AlbumArtistListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnAlbumArtistListActivated, this );
m_SongListCtrl->Unbind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnSongListActivated, this );
m_SongListCtrl->Unbind( wxEVT_LIST_COL_CLICK, &guLibPanel::OnSongListColClicked, this );
Unbind( wxEVT_MENU, &guLibPanel::OnGenrePlayClicked, this, ID_GENRE_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnGenreQueueClicked, this, ID_GENRE_ENQUEUE_AFTER_ALL, ID_GENRE_ENQUEUE_AFTER_ARTIST );
m_GenreListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnGenreCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnGenreSavePlayListClicked, this, ID_GENRE_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnLabelPlayClicked, this, ID_LABEL_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnLabelQueueClicked, this, ID_LABEL_ENQUEUE_AFTER_ALL, ID_LABEL_ENQUEUE_AFTER_ARTIST );
m_LabelsListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnLabelCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnLabelSavePlayListClicked, this, ID_LABEL_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistPlayClicked, this, ID_ARTIST_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistQueueClicked, this, ID_ARTIST_ENQUEUE_AFTER_ALL, ID_ARTIST_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistEditLabelsClicked, this, ID_ARTIST_EDITLABELS );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistEditTracksClicked, this, ID_ARTIST_EDITTRACKS );
m_ArtistListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnArtistCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistSavePlayListClicked, this, ID_ARTIST_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumPlayClicked, this, ID_ALBUM_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumQueueClicked, this, ID_ALBUM_ENQUEUE_AFTER_ALL, ID_ALBUM_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumEditLabelsClicked, this, ID_ALBUM_EDITLABELS );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumEditTracksClicked, this, ID_ALBUM_EDITTRACKS );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumDownloadCoverClicked, this, ID_ALBUM_MANUALCOVER );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumSelectCoverClicked, this, ID_ALBUM_SELECT_COVER );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumDeleteCoverClicked, this, ID_ALBUM_COVER_DELETE );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumEmbedCoverClicked, this, ID_ALBUM_COVER_EMBED );
m_AlbumListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnAlbumCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumSavePlayListClicked, this, ID_ALBUM_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnYearListPlayClicked, this, ID_YEAR_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnYearListQueueClicked, this, ID_YEAR_ENQUEUE_AFTER_ALL, ID_YEAR_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnYearListEditTracksClicked, this, ID_YEAR_EDITTRACKS );
m_YearListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnYearListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnYearSavePlayListClicked, this, ID_YEAR_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnRatingListPlayClicked, this, ID_RATING_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnRatingListQueueClicked, this, ID_RATING_ENQUEUE_AFTER_ALL, ID_RATING_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnRatingListEditTracksClicked, this, ID_RATING_EDITTRACKS );
m_RatingListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnRatingListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnArtistSavePlayListClicked, this, ID_RATING_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnPlayCountListPlayClicked, this, ID_PLAYCOUNT_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnPlayCountListQueueClicked, this, ID_PLAYCOUNT_ENQUEUE_AFTER_ALL, ID_PLAYCOUNT_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnPlayCountListEditTracksClicked, this, ID_PLAYCOUNT_EDITTRACKS );
m_PlayCountListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnPlayCountListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnPlayCountSavePlayListClicked, this, ID_PLAYCOUNT_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnComposerListPlayClicked, this, ID_COMPOSER_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnComposerListQueueClicked, this, ID_COMPOSER_ENQUEUE_AFTER_ALL, ID_COMPOSER_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnComposerListEditTracksClicked, this, ID_COMPOSER_EDITTRACKS );
m_ComposerListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnComposerListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnComposerSavePlayListClicked, this, ID_COMPOSER_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListPlayClicked, this, ID_ALBUMARTIST_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListQueueClicked, this, ID_ALBUMARTIST_ENQUEUE_AFTER_ALL, ID_ALBUMARTIST_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListEditTracksClicked, this, ID_ALBUMARTIST_EDITTRACKS );
m_AlbumArtistListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnAlbumArtistSavePlayListClicked, this, ID_ALBUMARTIST_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnSongPlayClicked, this, ID_TRACKS_PLAY );
Unbind( wxEVT_MENU, &guLibPanel::OnSongQueueClicked, this, ID_TRACKS_ENQUEUE_AFTER_ALL, ID_TRACKS_ENQUEUE_AFTER_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnSongsEditLabelsClicked, this, ID_TRACKS_EDITLABELS );
Unbind( wxEVT_MENU, &guLibPanel::OnSongsEditTracksClicked, this, ID_TRACKS_EDITTRACKS );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSavePlayListClicked, this, ID_TRACKS_SAVETOPLAYLIST );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSetRating, this, ID_TRACKS_SET_RATING_0, ID_TRACKS_SET_RATING_5 );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSetField, this, ID_TRACKS_SET_COLUMN );
Unbind( wxEVT_MENU, &guLibPanel::OnSongEditField, this, ID_TRACKS_EDIT_COLUMN );
m_SongListCtrl->Unbind( wxEVT_MENU, &guLibPanel::OnSongCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSelectGenre, this, ID_TRACKS_BROWSE_GENRE );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSelectArtist, this, ID_TRACKS_BROWSE_ARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSelectAlbumArtist, this, ID_TRACKS_BROWSE_ALBUMARTIST );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSelectComposer, this, ID_TRACKS_BROWSE_COMPOSER );
Unbind( wxEVT_MENU, &guLibPanel::OnSongSelectAlbum, this, ID_TRACKS_BROWSE_ALBUM );
Unbind( wxEVT_MENU, &guLibPanel::OnSongDeleteLibrary, this, ID_TRACKS_DELETE_LIBRARY );
Unbind( wxEVT_MENU, &guLibPanel::OnSongDeleteDrive, this, ID_TRACKS_DELETE_DRIVE );
Unbind( wxEVT_MENU, &guLibPanel::OnGoToSearch, this, ID_LIBRARY_SEARCH );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::CreateControls( void )
{
wxPanel * GenrePanel;
wxPanel * LabelsPanel;
wxPanel * AlbumPanel;
wxPanel * ArtistPanel;
wxBoxSizer * GenreSizer;
wxBoxSizer * LabelsSizer;
wxBoxSizer * ArtistSizer;
wxBoxSizer * AlbumSizer;
wxPanel * SongListPanel;
wxBoxSizer * SongListSizer;
guConfig * Config = ( guConfig * ) guConfig::Get();
bool ShowCloseButton = Config->ReadBool( CONFIG_KEY_GENERAL_SHOW_CLOSE_BUTTON, true, CONFIG_PATH_GENERAL );
GenreSizer = new wxBoxSizer( wxVERTICAL );
GenrePanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
m_GenreListCtrl = new guGeListBox( GenrePanel, this, m_Db, _( "Genres" ) );
GenreSizer->Add( m_GenreListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
GenrePanel->SetSizer( GenreSizer );
GenrePanel->Layout();
GenreSizer->Fit( GenrePanel );
m_AuiManager.AddPane( GenrePanel, wxAuiPaneInfo().Name( wxT( "Genres" ) ).Caption( _( "Genres" ) ).
MinSize( 50, 50 ).Row( 1 ).
Position( 1 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
LabelsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
LabelsSizer = new wxBoxSizer( wxVERTICAL );
m_LabelsListCtrl = new guTaListBox( LabelsPanel, this, m_Db, _( "Labels" ) );
LabelsSizer->Add( m_LabelsListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
LabelsPanel->SetSizer( LabelsSizer );
LabelsPanel->Layout();
LabelsSizer->Fit( LabelsPanel );
m_AuiManager.AddPane( LabelsPanel, wxAuiPaneInfo().Name( wxT( "Labels" ) ).Caption( _( "Labels" ) ).
MinSize( 50, 50 ).Row( 1 ).
Position( 0 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
ArtistPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
ArtistSizer = new wxBoxSizer( wxVERTICAL );
m_ArtistListCtrl = new guArListBox( ArtistPanel, this, m_Db, _( "Artists" ) );
ArtistSizer->Add( m_ArtistListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
ArtistPanel->SetSizer( ArtistSizer );
ArtistPanel->Layout();
ArtistSizer->Fit( ArtistPanel );
m_AuiManager.AddPane( ArtistPanel, wxAuiPaneInfo().Name( wxT( "Artists" ) ).Caption( _( "Artists" ) ).
MinSize( 50, 50 ).Row( 1 ).
Position( 2 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
AlbumPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
AlbumSizer = new wxBoxSizer( wxVERTICAL );
m_AlbumListCtrl = new guAlListBox( AlbumPanel, this, m_Db, _( "Albums" ) );
AlbumSizer->Add( m_AlbumListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
AlbumPanel->SetSizer( AlbumSizer );
AlbumPanel->Layout();
AlbumSizer->Fit( AlbumPanel );
m_AuiManager.AddPane( AlbumPanel, wxAuiPaneInfo().Name( wxT( "Albums" ) ).Caption( _( "Albums" ) ).
MinSize( 50, 50 ).Row( 1 ).
Position( 3 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Years
//
wxPanel * YearPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * YearsSizer = new wxBoxSizer( wxVERTICAL );
m_YearListCtrl = new guYeListBox( YearPanel, this, m_Db, _( "Years" ) );
YearsSizer->Add( m_YearListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
YearPanel->SetSizer( YearsSizer );
YearPanel->Layout();
YearsSizer->Fit( YearPanel );
m_AuiManager.AddPane( YearPanel, wxAuiPaneInfo().Name( wxT( "Years" ) ).Caption( _( "Years" ) ).
MinSize( 50, 50 ).Row( 2 ).
Position( 0 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Ratings
//
wxPanel * RatingPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * RatingSizer = new wxBoxSizer( wxVERTICAL );
m_RatingListCtrl = new guRaListBox( RatingPanel, this, m_Db, _( "Ratings" ) );
RatingSizer->Add( m_RatingListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
RatingPanel->SetSizer( RatingSizer );
RatingPanel->Layout();
RatingSizer->Fit( RatingPanel );
m_AuiManager.AddPane( RatingPanel, wxAuiPaneInfo().Name( wxT( "Ratings" ) ).Caption( _( "Ratings" ) ).
MinSize( 50, 50 ).Row( 2 ).
Position( 1 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Plays
//
wxPanel * PlayCountPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * PlayCountSizer = new wxBoxSizer( wxVERTICAL );
m_PlayCountListCtrl = new guPcListBox( PlayCountPanel, this, m_Db, _( "Plays" ) );
PlayCountSizer->Add( m_PlayCountListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
PlayCountPanel->SetSizer( PlayCountSizer );
PlayCountPanel->Layout();
PlayCountSizer->Fit( PlayCountPanel );
m_AuiManager.AddPane( PlayCountPanel, wxAuiPaneInfo().Name( wxT( "Plays" ) ).Caption( _( "Plays" ) ).
MinSize( 50, 50 ).Row( 2 ).
Position( 2 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Composers
//
wxPanel * ComposerPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * ComposerSizer = new wxBoxSizer( wxVERTICAL );
m_ComposerListCtrl = new guCoListBox( ComposerPanel, this, m_Db, _( "Composers" ) );
ComposerSizer->Add( m_ComposerListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
ComposerPanel->SetSizer( ComposerSizer );
ComposerPanel->Layout();
ComposerSizer->Fit( ComposerPanel );
m_AuiManager.AddPane( ComposerPanel, wxAuiPaneInfo().Name( wxT( "Composers" ) ).Caption( _( "Composers" ) ).
MinSize( 50, 50 ).Row( 2 ).
Position( 3 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Album Artists
//
wxPanel * AlbumArtistPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer * AlbumArtistSizer = new wxBoxSizer( wxVERTICAL );
m_AlbumArtistListCtrl = new guAAListBox( AlbumArtistPanel, this, m_Db, _( "Album Artist" ) );
AlbumArtistSizer->Add( m_AlbumArtistListCtrl, 1, wxEXPAND, LISTCTRL_BORDER );
AlbumArtistPanel->SetSizer( AlbumArtistSizer );
AlbumArtistPanel->Layout();
AlbumArtistSizer->Fit( AlbumArtistPanel );
m_AuiManager.AddPane( AlbumArtistPanel, wxAuiPaneInfo().Name( wxT( "AlbumArtists" ) ).Caption( _( "Album Artist" ) ).
MinSize( 50, 50 ).Row( 2 ).
Position( 4 ).Hide().
CloseButton( ShowCloseButton ).
Dockable( true ).Top() );
//
// Songs
//
SongListPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
SongListSizer = new wxBoxSizer( wxVERTICAL );
m_SongListCtrl = new guSoListBox( SongListPanel, m_MediaViewer, m_ConfigPath, guLISTVIEW_COLUMN_SELECT|guLISTVIEW_COLUMN_SORTING );
//ReloadSongs();
SongListSizer->Add( m_SongListCtrl, 1, wxEXPAND, 5 );
SongListPanel->SetSizer( SongListSizer );
SongListPanel->Layout();
SongListSizer->Fit( SongListPanel );
m_AuiManager.AddPane( SongListPanel, wxAuiPaneInfo().Name( wxT( "Tracks" ) ).Caption( _( "Tracks" ) ).
MinSize( 50, 50 ).
CenterPane() );
Bind( wxEVT_TIMER, &guLibPanel::OnSelChangedTimer, this, guPANEL_TIMER_SELECTION );
//
m_GenreListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnGenreListSelected, this );
m_GenreListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnGenreListActivated, this );
m_LabelsListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnLabelListSelected, this );
m_LabelsListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnLabelListActivated, this );
m_ArtistListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnArtistListSelected, this );
m_ArtistListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnArtistListActivated, this );
m_AlbumListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnAlbumListSelected, this );
m_AlbumListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnAlbumListActivated, this );
m_YearListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnYearListSelected, this );
m_YearListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnYearListActivated, this );
m_RatingListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnRatingListSelected, this );
m_RatingListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnRatingListActivated, this );
m_PlayCountListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnPlayCountListSelected, this );
m_PlayCountListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnPlayCountListActivated, this );
m_ComposerListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnComposerListSelected, this );
m_ComposerListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnComposerListActivated, this );
m_AlbumArtistListCtrl->Bind( wxEVT_LISTBOX, &guLibPanel::OnAlbumArtistListSelected, this );
m_AlbumArtistListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnAlbumArtistListActivated, this );
m_SongListCtrl->Bind( wxEVT_LISTBOX_DCLICK, &guLibPanel::OnSongListActivated, this );
m_SongListCtrl->Bind( wxEVT_LIST_COL_CLICK, &guLibPanel::OnSongListColClicked, this );
Bind( wxEVT_MENU, &guLibPanel::OnGenrePlayClicked, this, ID_GENRE_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnGenreQueueClicked, this, ID_GENRE_ENQUEUE_AFTER_ALL, ID_GENRE_ENQUEUE_AFTER_ARTIST );
m_GenreListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnGenreCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnGenreSavePlayListClicked, this, ID_GENRE_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnLabelPlayClicked, this, ID_LABEL_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnLabelQueueClicked, this, ID_LABEL_ENQUEUE_AFTER_ALL, ID_LABEL_ENQUEUE_AFTER_ARTIST );
m_LabelsListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnLabelCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnLabelSavePlayListClicked, this, ID_LABEL_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnArtistPlayClicked, this, ID_ARTIST_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnArtistQueueClicked, this, ID_ARTIST_ENQUEUE_AFTER_ALL, ID_ARTIST_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnArtistEditLabelsClicked, this, ID_ARTIST_EDITLABELS );
Bind( wxEVT_MENU, &guLibPanel::OnArtistEditTracksClicked, this, ID_ARTIST_EDITTRACKS );
m_ArtistListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnArtistCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnArtistSavePlayListClicked, this, ID_ARTIST_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnArtistCreateBestOfPlaylistClicked, this, ID_ARTIST_CREATE_BESTOF_PLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumPlayClicked, this, ID_ALBUM_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumQueueClicked, this, ID_ALBUM_ENQUEUE_AFTER_ALL, ID_ALBUM_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumEditLabelsClicked, this, ID_ALBUM_EDITLABELS );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumEditTracksClicked, this, ID_ALBUM_EDITTRACKS );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumDownloadCoverClicked, this, ID_ALBUM_MANUALCOVER );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumSelectCoverClicked, this, ID_ALBUM_SELECT_COVER );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumDeleteCoverClicked, this, ID_ALBUM_COVER_DELETE );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumEmbedCoverClicked, this, ID_ALBUM_COVER_EMBED );
m_AlbumListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnAlbumCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumSavePlayListClicked, this, ID_ALBUM_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumCreateBestOfPlaylistClicked, this, ID_ALBUM_CREATE_BESTOF_PLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnYearListPlayClicked, this, ID_YEAR_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnYearListQueueClicked, this, ID_YEAR_ENQUEUE_AFTER_ALL, ID_YEAR_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnYearListEditTracksClicked, this, ID_YEAR_EDITTRACKS );
m_YearListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnYearListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnYearSavePlayListClicked, this, ID_YEAR_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnRatingListPlayClicked, this, ID_RATING_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnRatingListQueueClicked, this, ID_RATING_ENQUEUE_AFTER_ALL, ID_RATING_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnRatingListEditTracksClicked, this, ID_RATING_EDITTRACKS );
m_RatingListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnRatingListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnArtistSavePlayListClicked, this, ID_RATING_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnPlayCountListPlayClicked, this, ID_PLAYCOUNT_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnPlayCountListQueueClicked, this, ID_PLAYCOUNT_ENQUEUE_AFTER_ALL, ID_PLAYCOUNT_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnPlayCountListEditTracksClicked, this, ID_PLAYCOUNT_EDITTRACKS );
m_PlayCountListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnPlayCountListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnPlayCountSavePlayListClicked, this, ID_PLAYCOUNT_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnComposerListPlayClicked, this, ID_COMPOSER_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnComposerListQueueClicked, this, ID_COMPOSER_ENQUEUE_AFTER_ALL, ID_COMPOSER_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnComposerListEditTracksClicked, this, ID_COMPOSER_EDITTRACKS );
m_ComposerListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnComposerListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnComposerSavePlayListClicked, this, ID_COMPOSER_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListPlayClicked, this, ID_ALBUMARTIST_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListQueueClicked, this, ID_ALBUMARTIST_ENQUEUE_AFTER_ALL, ID_ALBUMARTIST_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListEditTracksClicked, this, ID_ALBUMARTIST_EDITTRACKS );
m_AlbumArtistListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistListCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistSavePlayListClicked, this, ID_ALBUMARTIST_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnAlbumArtistCreateBestOfPlayListClicked, this, ID_ALBUMARTIST_CREATE_BESTOF_PLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnSongPlayClicked, this, ID_TRACKS_PLAY );
Bind( wxEVT_MENU, &guLibPanel::OnSongQueueClicked, this, ID_TRACKS_ENQUEUE_AFTER_ALL, ID_TRACKS_ENQUEUE_AFTER_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnSongsEditLabelsClicked, this, ID_TRACKS_EDITLABELS );
Bind( wxEVT_MENU, &guLibPanel::OnSongsEditTracksClicked, this, ID_TRACKS_EDITTRACKS );
Bind( wxEVT_MENU, &guLibPanel::OnSongSavePlayListClicked, this, ID_TRACKS_SAVETOPLAYLIST );
Bind( wxEVT_MENU, &guLibPanel::OnSongSetRating, this, ID_TRACKS_SET_RATING_0, ID_TRACKS_SET_RATING_5 );
Bind( wxEVT_MENU, &guLibPanel::OnSongSetField, this, ID_TRACKS_SET_COLUMN );
Bind( wxEVT_MENU, &guLibPanel::OnSongEditField, this, ID_TRACKS_EDIT_COLUMN );
m_SongListCtrl->Bind( wxEVT_MENU, &guLibPanel::OnSongCopyToClicked, this, ID_COPYTO_BASE, ID_COPYTO_BASE + guCOPYTO_MAXCOUNT );
Bind( wxEVT_MENU, &guLibPanel::OnSongSelectGenre, this, ID_TRACKS_BROWSE_GENRE );
Bind( wxEVT_MENU, &guLibPanel::OnSongSelectArtist, this, ID_TRACKS_BROWSE_ARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnSongSelectAlbumArtist, this, ID_TRACKS_BROWSE_ALBUMARTIST );
Bind( wxEVT_MENU, &guLibPanel::OnSongSelectComposer, this, ID_TRACKS_BROWSE_COMPOSER );
Bind( wxEVT_MENU, &guLibPanel::OnSongSelectAlbum, this, ID_TRACKS_BROWSE_ALBUM );
Bind( wxEVT_MENU, &guLibPanel::OnSongDeleteLibrary, this, ID_TRACKS_DELETE_LIBRARY );
Bind( wxEVT_MENU, &guLibPanel::OnSongDeleteDrive, this, ID_TRACKS_DELETE_DRIVE );
Bind( wxEVT_MENU, &guLibPanel::OnGoToSearch, this, ID_LIBRARY_SEARCH );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::LoadLastLayout( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxString LibraryLayout = Config->ReadStr( wxT( "Layout" ), wxEmptyString, m_ConfigPath );
if( Config->GetIgnoreLayouts() || LibraryLayout.IsEmpty() )
{
m_VisiblePanels = guPANEL_LIBRARY_VISIBLE_DEFAULT;
LibraryLayout = wxT( "layout2|name=Genres;caption=" ) + wxString( _( "Genres" ) );
LibraryLayout += wxT( ";state=2099196;dir=1;layer=0;row=1;pos=1;prop=113793;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Labels;caption=" ) + wxString( _( "Labels" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=1;pos=0;prop=66995;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Artists;caption=" ) + wxString( _( "Artists" ) );
LibraryLayout += wxT( ";state=2099196;dir=1;layer=0;row=1;pos=2;prop=80788;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Albums;caption=" ) + wxString( _( "Albums" ) );
LibraryLayout += wxT( ";state=2099196;dir=1;layer=0;row=1;pos=3;prop=138424;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Years;caption=" ) + wxString( _( "Years" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=2;pos=0;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Ratings;caption=" ) + wxString( _( "Ratings" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=2;pos=1;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Plays;caption=" ) + wxString( _( "Plays" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=2;pos=2;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Composers;caption=" ) + wxString( _( "Composers" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=2;pos=1;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=AlbumArtists;caption=" ) + wxString( _( "Album Artists" ) );
LibraryLayout += wxT( ";state=2099198;dir=1;layer=0;row=2;pos=0;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "name=Tracks;caption=" ) + wxString( _( "Tracks" ) );
LibraryLayout += wxT( ";state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=50;besth=50;minw=50;minh=50;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|" );
LibraryLayout += wxT( "dock_size(1,0,1)=190|dock_size(5,0,0)=52|" );
}
//m_AuiManager.LoadPerspective( LibraryLayout, true );
LoadPerspective( LibraryLayout, m_VisiblePanels );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::InitPanelData( void )
{
guLogMessage( wxT( "guLibPanel::IniPanelData( %i )" ), m_BaseCommand );
m_PanelNames.Empty();
m_PanelNames.Add( wxT( "Labels" ) );
m_PanelNames.Add( wxT( "Genres" ) );
m_PanelNames.Add( wxT( "Artists" ) );
m_PanelNames.Add( wxT( "Composers" ) );
m_PanelNames.Add( wxT( "AlbumArtists" ) );
m_PanelNames.Add( wxT( "Albums" ) );
m_PanelNames.Add( wxT( "Years" ) );
m_PanelNames.Add( wxT( "Ratings" ) );
m_PanelNames.Add( wxT( "Plays" ) );
m_PanelIds.Empty();
m_PanelIds.Add( guPANEL_LIBRARY_LABELS );
m_PanelIds.Add( guPANEL_LIBRARY_GENRES );
m_PanelIds.Add( guPANEL_LIBRARY_ARTISTS );
m_PanelIds.Add( guPANEL_LIBRARY_COMPOSERS );
m_PanelIds.Add( guPANEL_LIBRARY_ALBUMARTISTS );
m_PanelIds.Add( guPANEL_LIBRARY_ALBUMS );
m_PanelIds.Add( guPANEL_LIBRARY_YEARS );
m_PanelIds.Add( guPANEL_LIBRARY_RATINGS );
m_PanelIds.Add( guPANEL_LIBRARY_PLAYCOUNT );
m_PanelCmdIds.Empty();
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_LABELS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_GENRES );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_ARTISTS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_COMPOSERS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_ALBUMARTISTS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_ALBUMS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_YEARS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_RATINGS );
m_PanelCmdIds.Add( m_BaseCommand + guLIBRARY_ELEMENT_PLAYCOUNT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::ReloadControls( void )
{
// guLogMessage( wxT( "ReloadControls...%08X" ), m_VisiblePanels );
//m_Db->LoadCache();
m_UpdateLock = true;
ReloadLabels( false );
ReloadGenres( false );
ReloadAlbumArtists( false );
ReloadArtists( false );
ReloadComposers( false );
ReloadAlbums( false );
ReloadYears( false );
ReloadRatings( false );
ReloadPlayCounts( false );
ReloadSongs( false );
m_UpdateLock = false;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::ClearSearchText( void )
{
if( m_MediaViewer )
{
m_MediaViewer->ClearSearchText();
}
}
// -------------------------------------------------------------------------------- //
bool guLibPanel::DoTextSearch( const wxString &searchtext )
{
guLogMessage( wxT( "guLibPanel::DoTextSearch( '%s' )" ), searchtext.c_str() );
if( m_LastTextFilter == searchtext )
{
return true;
}
m_LastTextFilter = searchtext; //m_InputTextCtrl->GetValue();
if( !m_LastTextFilter.IsEmpty() )
{
if( m_LastTextFilter.Length() > 0 )
{
wxArrayString Words = guSplitWords( m_LastTextFilter );
m_Db->SetTeFilters( Words, m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadAlbums();
ReloadYears();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
// m_InputTextCtrl->ShowCancelButton( true );
}
return true;
}
else
{
wxArrayString Words;
//guLogMessage( wxT( "guLibPanel::SearchCancelled" ) );
//m_InputTextCtrl->Clear();
m_Db->SetTeFilters( Words, m_UpdateLock );
m_UpdateLock = true;
// if( !m_UpdateLock )
// {
ReloadLabels( false );
ReloadGenres( false );
ReloadAlbumArtists();
ReloadArtists( false );
ReloadComposers( false );
ReloadAlbums( false );
ReloadYears( false );
ReloadRatings( false );
ReloadPlayCounts( false );
ReloadSongs( false );
m_UpdateLock = false;
// }
// m_InputTextCtrl->ShowCancelButton( false );
return false;
}
}
// -------------------------------------------------------------------------------- //
// GenreListBox Events
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenreListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_GENRES;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenreListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_GenreListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenrePlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_GenreListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenreQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_GenreListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_GENRE_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenreCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_GenreListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGenreSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_GenreListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// LabelsListBox Events
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_LABELS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_LabelsListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_LabelsListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_LabelsListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_LABEL_ENQUEUE_AFTER_ALL );
}
}
//// -------------------------------------------------------------------------------- //
//void guLibPanel::OnLabelClearSelectClicked( wxCommandEvent &event )
//{
// m_LabelsListCtrl->ClearSelection();
//}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_LabelsListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdateLabels( void )
{
m_UpdateLock = true;
ReloadLabels( false );
ReloadGenres( false );
ReloadAlbumArtists( false );
ReloadArtists( false );
ReloadComposers( false );
ReloadAlbums( false );
ReloadRatings( false );
ReloadYears( false );
ReloadPlayCounts( false );
ReloadSongs( false );
m_UpdateLock = false;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnLabelSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_LabelsListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// ArtistListBox Events
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_ARTISTS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_ArtistListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_ArtistListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_ArtistListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_ARTIST_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistEditLabelsClicked( wxCommandEvent &event )
{
guListItems Artists;
m_ArtistListCtrl->GetSelectedItems( &Artists );
if( Artists.Count() )
{
guArrayListItems LabelSets = m_Db->GetArtistsLabels( m_ArtistListCtrl->GetSelectedItems() );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Artist Labels Editor" ), false, &Artists, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the artists files
m_Db->UpdateArtistsLabels( LabelSets );
}
UpdateLabels();
LabelEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::DoEditTracks( guTrackArray &tracks )
{
guImagePtrArray Images;
wxArrayString Lyrics;
wxArrayInt ChangedFlags;
int Count = tracks.Count();
for( int Index = Count - 1; Index >= 0; Index-- )
{
if( tracks[ Index ].m_Offset )
{
tracks.RemoveAt( Index );
}
}
if( tracks.Count() )
{
guTrackEditor * TrackEditor = new guTrackEditor( this, m_Db, &tracks, &Images, &Lyrics, &ChangedFlags );
if( TrackEditor )
{
if( TrackEditor->ShowModal() == wxID_OK )
{
UpdateTracks( tracks, Images, Lyrics, ChangedFlags );
// Update the track in database, playlist, etc
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &tracks );
}
guImagePtrArrayClean( &Images );
TrackEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdateTracks( const guTrackArray &tracks, const wxArrayInt &changedflags )
{
guImagePtrArray Images;
wxArrayString Lyrics;
UpdateTracks( tracks, Images, Lyrics, changedflags );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdateTracks( const guTrackArray &tracks, const guImagePtrArray &images,
const wxArrayString &lyrics, const wxArrayInt &changedflags )
{
m_MediaViewer->UpdateTracks( tracks, images, lyrics, changedflags );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdateTracksImages( const guTrackArray &tracks, const guImagePtrArray &images, const wxArrayInt &changedflags )
{
guUpdateImages( tracks, images, changedflags );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdateTracksLyrics( const guTrackArray &tracks, const wxArrayString &lyrics, const wxArrayInt &changedflags )
{
guUpdateLyrics( tracks, lyrics, changedflags );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_ArtistListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_ArtistListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_ArtistListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnArtistCreateBestOfPlaylistClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
if( m_ArtistListCtrl->GetSelectedSongs( &Tracks ) )
{
CreateBestOfPlaylist( Tracks[ 0 ] );
}
}
// -------------------------------------------------------------s------------------- //
// AlbumListBox Events
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_ALBUMS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false , CONFIG_PATH_GENERAL) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_ALBUM_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumEditLabelsClicked( wxCommandEvent &event )
{
guListItems Albums;
m_AlbumListCtrl->GetSelectedItems( &Albums );
if( Albums.Count() )
{
guArrayListItems LabelSets = m_Db->GetAlbumsLabels( m_AlbumListCtrl->GetSelectedItems() );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Albums Labels Editor" ),
false, &Albums, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
m_Db->UpdateAlbumsLabels( LabelSets );
}
LabelEditor->Destroy();
UpdateLabels();
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
//m_AlbumListCtrl->GetSelectedSongs( &Songs );
m_Db->GetAlbumsSongs( m_AlbumListCtrl->GetSelectedItems(), &Tracks, true );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumDownloadCoverClicked( wxCommandEvent &event )
{
wxArrayInt Albums = m_AlbumListCtrl->GetSelectedItems();
if( Albums.Count() )
{
m_MediaViewer->DownloadAlbumCover( Albums[ 0 ] );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumSelectCoverClicked( wxCommandEvent &event )
{
wxArrayInt Albums = m_AlbumListCtrl->GetSelectedItems();
if( Albums.Count() )
{
m_MediaViewer->SelectAlbumCover( Albums[ 0 ] );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::DoDeleteAlbumCover( const int albumid )
{
int CoverId = m_Db->GetAlbumCoverId( albumid );
if( CoverId > 0 )
{
wxString CoverPath = m_Db->GetCoverPath( CoverId );
if( !CoverPath.IsEmpty() )
{
if( !wxRemoveFile( CoverPath ) )
{
guLogError( wxT( "Could not remove the cover file '%s'" ), CoverPath.c_str() );
}
}
}
m_Db->SetAlbumCover( albumid, wxEmptyString );
wxCommandEvent evt( wxEVT_MENU, ID_ALBUM_COVER_CHANGED );
evt.SetInt( albumid );
evt.SetClientData( this );
wxPostEvent( guMainFrame::GetMainFrame(), evt );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumDeleteCoverClicked( wxCommandEvent &event )
{
wxArrayInt Albums = m_AlbumListCtrl->GetSelectedItems();
if( Albums.Count() )
{
if( wxMessageBox( _( "Are you sure to delete the selected album cover?" ),
_( "Confirm" ),
wxICON_QUESTION|wxYES_NO|wxNO_DEFAULT, this ) == wxYES )
{
m_MediaViewer->DeleteAlbumCover( Albums );
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumEmbedCoverClicked( wxCommandEvent &event )
{
wxArrayInt SelectedAlbums = m_AlbumListCtrl->GetSelectedItems();
int Count = SelectedAlbums.Count();
if( Count )
{
for( int Index = 0; Index < Count; Index++ )
{
m_MediaViewer->EmbedAlbumCover( SelectedAlbums[ Index ] );
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumCopyToClicked( wxCommandEvent &event )
{
guLogMessage( wxT( "guLibPanel::OnAlbumCopyToClicked %i" ), event.GetId() );
guTrackArray * Tracks = new guTrackArray();
m_AlbumListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_AlbumListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumCreateBestOfPlaylistClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
if( m_AlbumListCtrl->GetSelectedSongs( &Tracks ) )
{
CreateBestOfPlaylist( Tracks[ 0 ] );
}
}
// -------------------------------------------------------------------------------- //
// SongListBox Events
// -------------------------------------------------------------------------------- //
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_SongListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_SongListCtrl->GetSelectedSongs( &Songs );
if( !Songs.Count() )
{
m_SongListCtrl->GetAllSongs( &Songs );
}
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_SongListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_TRACKS_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::PlayAllTracks( const bool enqueue )
{
guTrackArray Tracks;
m_SongListCtrl->GetAllSongs( &Tracks );
if( enqueue )
m_PlayerPanel->AddToPlayList( Tracks );
else
m_PlayerPanel->SetPlayList( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongsEditLabelsClicked( wxCommandEvent &event )
{
guListItems Tracks;
m_SongListCtrl->GetSelectedItems( &Tracks, false );
if( Tracks.Count() )
{
guArrayListItems LabelSets = m_Db->GetSongsLabels( m_SongListCtrl->GetSelectedItems() );
guLabelEditor * LabelEditor = new guLabelEditor( this, m_Db, _( "Tracks Labels Editor" ), false, &Tracks, &LabelSets );
if( LabelEditor )
{
if( LabelEditor->ShowModal() == wxID_OK )
{
// Update the labels in the files
m_Db->UpdateSongsLabels( LabelSets );
}
UpdateLabels();
LabelEditor->Destroy();
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongsEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongCopyToClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
m_SongListCtrl->GetAllSongs( &Tracks );
if( Tracks.Count() )
{
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) new guTrackArray( Tracks ) );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SaveToPlayList( const wxArrayInt &tracks )
{
if( tracks.Count() )
{
guListItems PlayLists;
m_Db->GetPlayLists( &PlayLists, guPLAYLIST_TYPE_STATIC );
guPlayListAppend * PlayListAppendDlg = new guPlayListAppend( guMainFrame::GetMainFrame(), m_Db, &tracks, &PlayLists );
if( PlayListAppendDlg->ShowModal() == wxID_OK )
{
int PLId;
int Selected = PlayListAppendDlg->GetSelectedPlayList();
if( Selected == -1 )
{
wxString PLName = PlayListAppendDlg->GetPlaylistName();
if( PLName.IsEmpty() )
{
PLName = _( "UnNamed" );
}
PLId = m_Db->CreateStaticPlayList( PLName, tracks );
}
else
{
PLId = PlayLists[ Selected ].m_Id;
wxArrayInt OldSongs;
m_Db->GetPlayListSongIds( PLId, &OldSongs );
if( PlayListAppendDlg->GetSelectedPosition() == 0 ) // BEGIN
{
m_Db->UpdateStaticPlayList( PLId, tracks );
m_Db->AppendStaticPlayList( PLId, OldSongs );
}
else // END
{
m_Db->AppendStaticPlayList( PLId, tracks );
}
}
m_Db->UpdateStaticPlayListFile( PLId );
UpdatePlaylists();
}
PlayListAppendDlg->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::CreateBestOfPlaylist( const guTrack &track )
{
m_MediaViewer->CreateBestOfPlaylist( track );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
else
{
m_SongListCtrl->GetAllSongs( &Tracks );
count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdatePlaylists( void )
{
m_MediaViewer->UpdatePlaylists();
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSetRating( wxCommandEvent &event )
{
int Rating = event.GetId() - ID_TRACKS_SET_RATING_0;
//guLogMessage( wxT( "OnSongSetRating( %i )" ), Rating );
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
m_MediaViewer->SetTracksRating( Tracks, Rating );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSetField( wxCommandEvent &event )
{
int ColumnId = m_SongListCtrl->GetColumnId( m_SongListCtrl->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxVariant NewData = m_SongListCtrl->GetLastDataClicked();
//guLogMessage( wxT( "Setting Data to : %s" ), NewData.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = NewData.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = NewData.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = NewData.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = NewData.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = NewData.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = NewData.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = NewData.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = NewData.GetLong();
break;
}
}
UpdateTracks( Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongEditField( wxCommandEvent &event )
{
int ColumnId = m_SongListCtrl->GetColumnId( m_SongListCtrl->GetLastColumnClicked() );
//guLogMessage( wxT( "guLibPanel::OnSongSetField %i" ), ColumnId );
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxString Label = m_SongListCtrl->GetColumnNames()[ ColumnId ];
wxVariant DefValue = m_SongListCtrl->GetLastDataClicked();
wxArrayString Items;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
wxVariant Value;
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Value = ( long ) Track->m_Number;
break;
case guSONGS_COLUMN_TITLE :
Value = Track->m_SongName;
break;
case guSONGS_COLUMN_ARTIST :
Value = Track->m_ArtistName;
break;
case guSONGS_COLUMN_ALBUMARTIST :
Value = Track->m_AlbumArtist;
break;
case guSONGS_COLUMN_ALBUM :
Value = Track->m_AlbumName;
break;
case guSONGS_COLUMN_GENRE :
Value = Track->m_GenreName;
break;
case guSONGS_COLUMN_COMPOSER :
Value = Track->m_Composer;
break;
case guSONGS_COLUMN_DISK :
Value = Track->m_Disk;
break;
case guSONGS_COLUMN_YEAR :
Value = ( long ) Track->m_Year;
break;
case guSONGS_COLUMN_PLAYCOUNT :
Value = ( long ) Track->m_PlayCount;
}
if( Items.Index( Value.GetString() ) == wxNOT_FOUND )
Items.Add( Value.GetString() );
}
guEditWithOptions * FieldEditor = new guEditWithOptions( this, _( "Field Editor" ), Label, DefValue.GetString(), Items );
if( FieldEditor )
{
if( FieldEditor->ShowModal() == wxID_OK )
{
DefValue = FieldEditor->GetData();
//guLogMessage( wxT( "Setting Data to : %s" ), DefValue.GetString().c_str() );
// This should be done in a thread for huge selections of tracks...
wxArrayInt ChangedFlags;
int Count = Tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
ChangedFlags.Add( guTRACK_CHANGED_DATA_TAGS );
guTrack * Track = &Tracks[ Index ];
switch( ColumnId )
{
case guSONGS_COLUMN_NUMBER :
Track->m_Number = DefValue.GetLong();
break;
case guSONGS_COLUMN_TITLE :
Track->m_SongName = DefValue.GetString();
break;
case guSONGS_COLUMN_ARTIST :
Track->m_ArtistName = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUMARTIST :
Track->m_AlbumArtist = DefValue.GetString();
break;
case guSONGS_COLUMN_ALBUM :
Track->m_AlbumName = DefValue.GetString();
break;
case guSONGS_COLUMN_GENRE :
Track->m_GenreName = DefValue.GetString();
break;
case guSONGS_COLUMN_COMPOSER :
Track->m_Composer = DefValue.GetString();
break;
case guSONGS_COLUMN_DISK :
Track->m_Disk = DefValue.GetString();
break;
case guSONGS_COLUMN_YEAR :
Track->m_Year = DefValue.GetLong();
break;
case guSONGS_COLUMN_PLAYCOUNT :
ChangedFlags[ Index ] = guTRACK_CHANGED_DATA_RATING;
Track->m_PlayCount = DefValue.GetLong();
}
}
UpdateTracks( Tracks, ChangedFlags );
m_MediaViewer->UpdatedTracks( guUPDATED_TRACKS_NONE, &Tracks );
}
FieldEditor->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongListColClicked( wxListEvent &event )
{
int ColId = m_SongListCtrl->GetColumnId( event.m_col );
if( ColId == guSONGS_COLUMN_OFFSET )
return;
m_SongListCtrl->SetTracksOrder( ColId );
// Create the Columns
wxArrayString ColumnNames = m_SongListCtrl->GetColumnNames();
int CurColId;
int count = ColumnNames.Count();
for( int index = 0; index < count; index++ )
{
CurColId = m_SongListCtrl->GetColumnId( index );
m_SongListCtrl->SetColumnLabel( index,
ColumnNames[ CurColId ] + ( ( ColId == CurColId ) ? ( m_SongListCtrl->GetTracksOrderDesc() ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
}
ReloadSongs();
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSelectGenre( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt * Genres = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Genres->Index( Tracks[ index ].m_GenreId ) == wxNOT_FOUND )
{
Genres->Add( Tracks[ index ].m_GenreId );
}
}
SelectGenres( Genres );
delete Genres;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSelectArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt * Artists = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Artists->Index( Tracks[ index ].m_ArtistId ) == wxNOT_FOUND )
{
Artists->Add( Tracks[ index ].m_ArtistId );
}
}
SelectArtists( Artists );
delete Artists;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSelectAlbumArtist( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt * AlbumArtists = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( AlbumArtists->Index( Tracks[ index ].m_AlbumArtistId ) == wxNOT_FOUND )
{
AlbumArtists->Add( Tracks[ index ].m_AlbumArtistId );
}
}
SelectAlbumArtists( AlbumArtists );
delete AlbumArtists;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSelectComposer( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt * Composers = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Composers->Index( Tracks[ index ].m_ComposerId ) == wxNOT_FOUND )
{
Composers->Add( Tracks[ index ].m_ComposerId );
}
}
SelectComposers( Composers );
delete Composers;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongSelectAlbum( wxCommandEvent &event )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
wxArrayInt * Albums = new wxArrayInt();
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
if( Albums->Index( Tracks[ index ].m_AlbumId ) == wxNOT_FOUND )
{
Albums->Add( Tracks[ index ].m_AlbumId );
}
}
SelectAlbums( Albums );
delete Albums;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SetSelection( const int type, const int id )
{
switch( type )
{
case guMEDIAVIEWER_SELECT_TRACK : SelectTrack( id ); break;
case guMEDIAVIEWER_SELECT_ARTIST : SelectArtist( id ); break;
case guMEDIAVIEWER_SELECT_ALBUM : SelectAlbum( id ); break;
case guMEDIAVIEWER_SELECT_ALBUMARTIST : SelectAlbumArtist( id ); break;
case guMEDIAVIEWER_SELECT_COMPOSER : SelectComposer( id ); break;
case guMEDIAVIEWER_SELECT_YEAR : SelectYear( id ); break;
case guMEDIAVIEWER_SELECT_GENRE :
{
wxArrayInt Genres;
Genres.Add( id );
SelectGenres( &Genres );
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectTrack( const int trackid )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadAlbums();
m_UpdateLock = false;
ReloadSongs();
m_SongListCtrl->SetSelection( m_Db->GetTrackIndex( trackid ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectAlbum( const int albumid )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadAlbums();
m_UpdateLock = false;
m_AlbumListCtrl->SetSelection( m_AlbumListCtrl->FindAlbum( albumid ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectArtist( const int artistid )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
m_UpdateLock = false;
m_ArtistListCtrl->SetSelection( m_ArtistListCtrl->FindArtist( artistid ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectAlbumArtist( const int albumartistid )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
m_UpdateLock = false;
m_AlbumArtistListCtrl->SetSelection( m_AlbumArtistListCtrl->FindItemId( albumartistid ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectComposer( const int composerid )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadComposers();
m_UpdateLock = false;
m_ComposerListCtrl->SetSelection( m_ComposerListCtrl->FindItemId( composerid ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectYear( const int year )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadYears();
m_UpdateLock = false;
m_YearListCtrl->SetSelection( m_YearListCtrl->FindYear( year ) );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectAlbumName( const wxString &album )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadAlbums();
m_UpdateLock = false;
m_AlbumListCtrl->SelectAlbumName( album );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectArtistName( const wxString &artist )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
m_UpdateLock = false;
m_ArtistListCtrl->SelectArtistName( artist );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectGenres( wxArrayInt * genres )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
m_UpdateLock = false;
m_GenreListCtrl->SetSelectedItems( * genres );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectArtists( wxArrayInt * artists )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
m_UpdateLock = false;
m_ArtistListCtrl->SetSelectedItems( * artists );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectAlbumArtists( wxArrayInt * ids )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadComposers();
ReloadAlbumArtists();
// ReloadArtists();
m_UpdateLock = false;
m_AlbumArtistListCtrl->SetSelectedItems( * ids );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectComposers( wxArrayInt * ids )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadComposers();
// ReloadAlbumArtists();
// ReloadArtists();
m_UpdateLock = false;
m_ComposerListCtrl->SetSelectedItems( * ids );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::SelectAlbums( wxArrayInt * albums )
{
wxArrayString Words;
m_UpdateLock = true;
m_LastTextFilter = wxEmptyString;
m_Db->SetTeFilters( Words, false );
ClearSearchText();
ReloadLabels();
ReloadGenres();
ReloadAlbumArtists();
ReloadArtists();
ReloadComposers();
ReloadAlbums();
m_UpdateLock = false;
m_AlbumListCtrl->SetSelectedItems( * albums );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_YEARS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_YearListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_YearListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_YearListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_YEAR_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_YearListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearListCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_YearListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnYearSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_YearListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// Rating List Box
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_RATINGS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_RatingListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_RatingListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_RatingListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_RATING_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_RatingListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingListCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_RatingListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnRatingSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_RatingListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// PlayCount List Box
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_PLAYCOUNT;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_PlayCountListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_PlayCountListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_PlayCountListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_PLAYCOUNT_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_PlayCountListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountListCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_PlayCountListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnPlayCountSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_PlayCountListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// Composers List Box
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_COMPOSERS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_ComposerListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_ComposerListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_ComposerListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_COMPOSER_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_ComposerListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerListCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_ComposerListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnComposerSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_ComposerListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
// Album Artists List Box
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListSelected( wxCommandEvent &event )
{
if( m_UpdateLock )
return;
m_SelChangedObject = guPANEL_LIBRARY_ALBUMARTISTS;
if( m_SelChangedTimer.IsRunning() )
m_SelChangedTimer.Stop();
m_SelChangedTimer.Start( guPANEL_TIMER_SELCHANGED, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListActivated( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumArtistListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
if( Config->ReadBool( CONFIG_KEY_GENERAL_ACTION_ENQUEUE, false, CONFIG_PATH_GENERAL ) )
{
m_PlayerPanel->AddToPlayList( Songs );
}
else
{
m_PlayerPanel->SetPlayList( Songs );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListPlayClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumArtistListCtrl->GetSelectedSongs( &Songs );
m_PlayerPanel->SetPlayList( Songs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListQueueClicked( wxCommandEvent &event )
{
guTrackArray Songs;
m_AlbumArtistListCtrl->GetSelectedSongs( &Songs );
if( Songs.Count() )
{
m_PlayerPanel->AddToPlayList( Songs, true, event.GetId() - ID_ALBUMARTIST_ENQUEUE_AFTER_ALL );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListEditTracksClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
m_AlbumArtistListCtrl->GetSelectedSongs( &Tracks );
if( !Tracks.Count() )
return;
DoEditTracks( Tracks );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistListCopyToClicked( wxCommandEvent &event )
{
guTrackArray * Tracks = new guTrackArray();
m_AlbumArtistListCtrl->GetSelectedSongs( Tracks );
int Index = event.GetId() - ID_COPYTO_BASE;
if( Index >= guCOPYTO_DEVICE_BASE )
{
Index -= guCOPYTO_DEVICE_BASE;
event.SetId( ID_MAINFRAME_COPYTODEVICE_TRACKS );
}
else
{
event.SetId( ID_MAINFRAME_COPYTO );
}
event.SetInt( Index );
event.SetClientData( ( void * ) Tracks );
wxPostEvent( guMainFrame::GetMainFrame(), event );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistSavePlayListClicked( wxCommandEvent &event )
{
wxArrayInt NewSongs;
guTrackArray Tracks;
m_AlbumArtistListCtrl->GetSelectedSongs( &Tracks );
int count = Tracks.Count();
for( int index = 0; index < count; index++ )
{
NewSongs.Add( Tracks[ index ].m_SongId );
}
SaveToPlayList( NewSongs );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnAlbumArtistCreateBestOfPlayListClicked( wxCommandEvent &event )
{
guTrackArray Tracks;
if( m_AlbumArtistListCtrl->GetSelectedSongs( &Tracks ) )
{
CreateBestOfPlaylist( Tracks[ 0 ] );
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSelChangedTimer( wxTimerEvent &event )
{
DoSelectionChanged();
m_SelChangedObject = 0;
}
// -------------------------------------------------------------------------------- //
void guLibPanel::DoSelectionChanged( void )
{
switch( m_SelChangedObject )
{
case guPANEL_LIBRARY_TEXTSEARCH :
{
break;
}
case guPANEL_LIBRARY_LABELS :
{
m_Db->SetLaFilters( m_LabelsListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadGenres();
ReloadComposers();
ReloadAlbumArtists();
ReloadArtists();
ReloadAlbums();
ReloadYears();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
//
//
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_GENRES :
{
//wxLongLong time = wxGetLocalTimeMillis();
m_Db->SetGeFilters( m_GenreListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadComposers();
ReloadAlbumArtists();
ReloadArtists();
ReloadYears();
ReloadAlbums();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
//time = wxGetLocalTimeMillis() - time;;
//guLogWarning( wxT( "Genre Time : %u ms" ), time.GetLo() );
break;
}
case guPANEL_LIBRARY_ARTISTS :
{
m_Db->SetArFilters( m_ArtistListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadAlbums();
ReloadYears();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_YEARS :
{
m_Db->SetYeFilters( m_YearListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadAlbums();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_ALBUMS :
{
m_Db->SetAlFilters( m_AlbumListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_RATINGS :
{
m_Db->SetRaFilters( m_RatingListCtrl->GetSelectedItems() );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_PLAYCOUNT :
{
m_Db->SetPcFilters( m_PlayCountListCtrl->GetSelectedItems() );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_COMPOSERS :
{
m_Db->SetCoFilters( m_ComposerListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
ReloadAlbumArtists();
ReloadArtists();
ReloadYears();
ReloadAlbums();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
break;
}
case guPANEL_LIBRARY_ALBUMARTISTS :
{
m_Db->SetAAFilters( m_AlbumArtistListCtrl->GetSelectedItems(), m_UpdateLock );
if( !m_UpdateLock )
{
m_UpdateLock = true;
//ReloadComposers();
ReloadArtists();
ReloadYears();
ReloadAlbums();
ReloadRatings();
ReloadPlayCounts();
ReloadSongs();
m_UpdateLock = false;
}
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongDeleteLibrary( wxCommandEvent &event )
{
if( m_SongListCtrl->GetSelectedCount() )
{
if( wxMessageBox( wxT( "Are you sure to remove the selected tracks from your library?" ),
wxT( "Remove tracks from library" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
//
m_Db->DeleteLibraryTracks( &Tracks, true );
//
m_SongListCtrl->ClearSelectedItems();
ReloadControls();
}
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnSongDeleteDrive( wxCommandEvent &event )
{
if( m_SongListCtrl->GetSelectedCount() )
{
if( wxMessageBox( _( "Are you sure to delete the selected tracks from your drive?\nThis will permanently erase the selected tracks." ),
_( "Remove tracks from drive" ), wxICON_QUESTION|wxYES|wxNO|wxNO_DEFAULT ) == wxYES )
{
guTrackArray Tracks;
m_SongListCtrl->GetSelectedSongs( &Tracks );
//
m_MediaViewer->DeleteTracks( &Tracks );
//
m_SongListCtrl->ClearSelectedItems();
ReloadControls();
}
}
}
// -------------------------------------------------------------------------------- //
int guLibPanel::GetContextMenuFlags( void )
{
return m_MediaViewer->GetContextMenuFlags();
}
// -------------------------------------------------------------------------------- //
void guLibPanel::CreateContextMenu( wxMenu * menu, const int windowid )
{
m_MediaViewer->CreateContextMenu( menu, windowid );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::CreateCopyToMenu( wxMenu * menu )
{
m_MediaViewer->CreateCopyToMenu( menu );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::OnGoToSearch( wxCommandEvent &event )
{
if( m_MediaViewer )
{
m_MediaViewer->GoToSearch();
}
}
// -------------------------------------------------------------------------------- //
void guLibPanel::NormalizeTracks( guTrackArray * tracks, const bool isdrag )
{
if( m_MediaViewer )
m_MediaViewer->NormalizeTracks( tracks, isdrag );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::AlbumCoverChanged( void )
{
ReloadAlbums( false );
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdatedTracks( const guTrackArray * tracks )
{
// if( m_SongListCtrl )
// m_SongListCtrl->UpdatedTracks( tracks );
ReloadControls();
}
// -------------------------------------------------------------------------------- //
void guLibPanel::UpdatedTrack( const guTrack * track )
{
// if( m_SongListCtrl )
// m_SongListCtrl->UpdatedTrack( track );
ReloadControls();
}
}
// -------------------------------------------------------------------------------- //
| 104,817
|
C++
|
.cpp
| 2,490
| 35.663454
| 178
| 0.573986
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,625
|
SoListBox.cpp
|
anonbeat_guayadeque/src/ui/mediaviewer/library/SoListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "SoListBox.h"
#include "Accelerators.h"
#include "Config.h" // Configuration
#include "EventCommandIds.h"
#include "Images.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "OnlineLinks.h"
#include "Utils.h"
#include "RatingCtrl.h"
#include "MediaViewer.h"
#include <wx/imaglist.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guSoListBox::guSoListBox( wxWindow * parent, guMediaViewer * mediaviewer, wxString confname, long style ) :
guListView( parent, style|wxLB_MULTIPLE|guLISTVIEW_ALLOWDRAG|guLISTVIEW_COLUMN_CLICK_EVENTS,
wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL|wxVSCROLL )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
m_MediaViewer = mediaviewer;
m_Db = mediaviewer->GetDb();
m_ConfName = confname;
m_ItemsFirst = wxNOT_FOUND;
m_ItemsLast = wxNOT_FOUND;
m_LastColumnRightClicked = wxNOT_FOUND;
m_TracksOrder = Config->ReadNum( wxT( "TracksOrder" ), 0, confname );
m_TracksOrderDesc = Config->ReadBool( wxT( "TracksOrderDesc" ), 0, confname );
m_Db->SetTracksOrder( m_TracksOrder );
m_Db->SetTracksOrderDesc( m_TracksOrderDesc );
m_ColumnNames.Add( wxT( "#" ) );
m_ColumnNames.Add( _( "Title" ) );
m_ColumnNames.Add( _( "Artist" ) );
m_ColumnNames.Add( _( "Album Artist" ) );
m_ColumnNames.Add( _( "Album" ) );
m_ColumnNames.Add( _( "Genre" ) );
m_ColumnNames.Add( _( "Composer" ) );
m_ColumnNames.Add( _( "Disc" ) );
m_ColumnNames.Add( _( "Length" ) );
m_ColumnNames.Add( _( "Year" ) );
m_ColumnNames.Add( _( "Bit Rate" ) );
m_ColumnNames.Add( _( "Rating" ) );
m_ColumnNames.Add( _( "Plays" ) );
m_ColumnNames.Add( _( "Last Played" ) );
m_ColumnNames.Add( _( "Added" ) );
m_ColumnNames.Add( _( "Format" ) );
m_ColumnNames.Add( _( "Path" ) );
m_ColumnNames.Add( _( "Offset" ) );
int ColId;
wxString ColName;
int Count = m_ColumnNames.Count();
for( int Index = 0; Index < Count; Index++ )
{
ColId = Config->ReadNum( wxString::Format( wxT( "id%u" ), Index ), Index, m_ConfName + wxT( "/columns/ids" ) );
ColName = m_ColumnNames[ ColId ];
if( style & guLISTVIEW_COLUMN_SORTING )
ColName += ( ( ColId == m_TracksOrder ) ? ( m_TracksOrderDesc ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString );
guListViewColumn * Column = new guListViewColumn(
ColName,
ColId,
Config->ReadNum( wxString::Format( wxT( "width%u" ), Index ), 80, m_ConfName + wxT( "/columns/widths" ) ),
Config->ReadBool( wxString::Format( wxT( "show%u" ), Index ), true, m_ConfName + wxT( "/columns/shows" ) )
);
InsertColumn( Column );
}
m_NormalStar = new wxBitmap( guImage( ( guIMAGE_INDEX ) ( guIMAGE_INDEX_star_normal_tiny + GURATING_STYLE_MID ) ) );
m_SelectStar = new wxBitmap( guImage( ( guIMAGE_INDEX ) ( guIMAGE_INDEX_star_highlight_tiny + GURATING_STYLE_MID ) ) );
Bind( wxEVT_MENU, &guSoListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Bind( wxEVT_MENU, &guSoListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Bind( guEVT_LISTBOX_ITEM_COL_CLICKED, &guSoListBox::OnItemColumnClicked, this );
Bind( guEVT_LISTBOX_ITEM_COL_RCLICKED, &guSoListBox::OnItemColumnRClicked, this );
Bind( guConfigUpdatedEvent, &guSoListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Bind( wxEVT_MENU, &guSoListBox::OnCreateSmartPlaylist, this, ID_PLAYLIST_SMART_PLAYLIST );
Bind( wxEVT_MENU, &guSoListBox::OnCreateBestOfPlaylist, this, ID_PLAYER_PLAYLIST_CREATE_BESTOF );
CreateAcceleratorTable();
ReloadItems();
}
// -------------------------------------------------------------------------------- //
guSoListBox::~guSoListBox()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Config->WriteNum( wxT( "TracksOrder" ), m_TracksOrder, m_ConfName );
Config->WriteBool( wxT( "TracksOrderDesc" ), m_TracksOrderDesc, m_ConfName );
//int ColId;
int count = guSONGS_COLUMN_COUNT;
for( int index = 0; index < count; index++ )
{
Config->WriteNum( wxString::Format( wxT( "id%u" ), index ),
( * m_Columns )[ index ].m_Id,
m_ConfName + wxT( "/columns/ids" ) );
Config->WriteNum( wxString::Format( wxT( "width%u" ), index ),
( * m_Columns )[ index ].m_Width,
m_ConfName + wxT( "/columns/widths" ) );
Config->WriteBool( wxString::Format( wxT( "show%u" ), index ),
( * m_Columns )[ index ].m_Enabled,
m_ConfName + wxT( "/columns/shows" ) );
}
if( m_NormalStar )
delete m_NormalStar;
if( m_SelectStar )
delete m_SelectStar;
Unbind( wxEVT_MENU, &guSoListBox::OnSearchLinkClicked, this, ID_LINKS_BASE, ID_LINKS_BASE + guLINKS_MAXCOUNT );
Unbind( wxEVT_MENU, &guSoListBox::OnCommandClicked, this, ID_COMMANDS_BASE, ID_COMMANDS_BASE + guCOMMANDS_MAXCOUNT );
Unbind( guEVT_LISTBOX_ITEM_COL_CLICKED, &guSoListBox::OnItemColumnClicked, this );
Unbind( guEVT_LISTBOX_ITEM_COL_RCLICKED, &guSoListBox::OnItemColumnRClicked, this );
Unbind( guConfigUpdatedEvent, &guSoListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
Unbind( wxEVT_MENU, &guSoListBox::OnCreateSmartPlaylist, this, ID_PLAYLIST_SMART_PLAYLIST );
Unbind( wxEVT_MENU, &guSoListBox::OnCreateBestOfPlaylist, this, ID_PLAYER_PLAYLIST_CREATE_BESTOF );
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::CreateAcceleratorTable( void )
{
wxAcceleratorTable AccelTable;
wxArrayInt AliasAccelCmds;
wxArrayInt RealAccelCmds;
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SAVE );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITLABELS );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_EDITTRACKS );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
AliasAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
AliasAccelCmds.Add( ID_PLAYER_PLAYLIST_SEARCH );
RealAccelCmds.Add( ID_TRACKS_SAVETOPLAYLIST );
RealAccelCmds.Add( ID_TRACKS_EDITLABELS );
RealAccelCmds.Add( ID_TRACKS_EDITTRACKS );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALL );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_TRACK );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ALBUM );
RealAccelCmds.Add( ID_TRACKS_ENQUEUE_AFTER_ARTIST );
RealAccelCmds.Add( ID_LIBRARY_SEARCH );
if( guAccelDoAcceleratorTable( AliasAccelCmds, RealAccelCmds, AccelTable ) )
{
SetAcceleratorTable( AccelTable );
}
}
// -------------------------------------------------------------------------------- //
wxString guSoListBox::OnGetItemText( const int row, const int col ) const
{
guTrack * Track;
//guLogMessage( wxT( "GetItemText( %i, %i ) %i-%i %i" ), row, col, m_ItemsFirst, m_ItemsLast, m_Items.Count() );
Track = &m_Items[ row - m_ItemsFirst ];
switch( ( * m_Columns )[ col ].m_Id )
{
case guSONGS_COLUMN_NUMBER :
if( Track->m_Number )
return wxString::Format( wxT( "%u" ), Track->m_Number );
else
return wxEmptyString;
case guSONGS_COLUMN_TITLE :
return Track->m_SongName;
case guSONGS_COLUMN_ARTIST :
return Track->m_ArtistName;
case guSONGS_COLUMN_ALBUMARTIST :
return Track->m_AlbumArtist;
case guSONGS_COLUMN_ALBUM :
return Track->m_AlbumName;
case guSONGS_COLUMN_GENRE :
return Track->m_GenreName;
case guSONGS_COLUMN_COMPOSER :
return Track->m_Composer;
case guSONGS_COLUMN_DISK :
return Track->m_Disk;
case guSONGS_COLUMN_LENGTH :
return LenToString( Track->m_Length );
case guSONGS_COLUMN_YEAR :
if( Track->m_Year )
return wxString::Format( wxT( "%u" ), Track->m_Year );
else
return wxEmptyString;
case guSONGS_COLUMN_BITRATE :
return wxString::Format( wxT( "%u" ), Track->m_Bitrate );
case guSONGS_COLUMN_RATING :
return wxString::Format( wxT( "%i" ), Track->m_Rating );
case guSONGS_COLUMN_PLAYCOUNT :
{
if( Track->m_PlayCount )
return wxString::Format( wxT( "%u" ), Track->m_PlayCount );
break;
}
case guSONGS_COLUMN_LASTPLAY :
{
if( Track->m_LastPlay )
{
wxDateTime LastPlay;
LastPlay.Set( ( time_t ) Track->m_LastPlay );
return LastPlay.FormatDate();
}
else
return _( "Never" );
}
case guSONGS_COLUMN_ADDEDDATE :
{
wxDateTime AddedDate;
AddedDate.Set( ( time_t ) Track->m_AddedTime );
return AddedDate.FormatDate();
}
case guSONGS_COLUMN_FORMAT :
{
return Track->m_Format;
}
case guSONGS_COLUMN_FILEPATH :
{
return Track->m_FileName; // contains both path and filename
}
case guSONGS_COLUMN_OFFSET :
if( Track->m_Offset )
return LenToString( Track->m_Offset );
else
return wxEmptyString;
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
void guSoListBox::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
if( ( * m_Columns )[ col ].m_Id == guSONGS_COLUMN_RATING )
{
dc.SetBackgroundMode( wxTRANSPARENT );
int x;
int w = ( ( GURATING_STYLE_MID * 2 ) + GURATING_IMAGE_SIZE );
for( x = 0; x < 5; x++ )
{
dc.DrawBitmap( ( x >= m_Items[ row - m_ItemsFirst ].m_Rating ) ? * m_NormalStar : * m_SelectStar,
rect.x + 3 + ( w * x ), rect.y + 3, true );
}
}
else
{
guListView::DrawItem( dc, rect, row, col );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::ItemsCheckRange( const int start, const int end )
{
//guLogMessage( wxT( "guSoListBox::ItemsCheckRange( %i, %i )" ), start, end );
if( m_ItemsFirst != start || m_ItemsLast != end )
{
m_Items.Empty();
m_Db->GetSongs( &m_Items, start, end );
m_ItemsFirst = start;
m_ItemsLast = end;
}
//guLogMessage( wxT( "Updated the items... %i" ), m_Items );
}
// -------------------------------------------------------------------------------- //
void guSoListBox::GetItemsList( void )
{
//m_Db->GetSongs( &m_Items, GetVisibleRowsBegin(), GetVisibleRowsEnd() );
SetItemCount( m_Db->GetSongsCount() );
wxCommandEvent event( wxEVT_MENU, ID_MAINFRAME_UPDATE_SELINFO );
AddPendingEvent( event );
}
// -------------------------------------------------------------------------------- //
void guSoListBox::ReloadItems( bool reset )
{
//guLogMessage( wxT( "guSoListBox::ReloadItems( %i )"), reset );
//
wxArrayInt Selection;
int FirstVisible = GetVisibleRowsBegin();
if( reset )
SetSelection( -1 );
else
Selection = GetSelectedIndexs( false );
m_ItemsMutex.Lock();
m_Items.Empty();
m_ItemsFirst = -1;
m_ItemsLast = -1;
GetItemsList();
//SetItemCount( m_Items.Count() );
m_ItemsMutex.Unlock();
if( !reset )
{
SetSelectedIndexs( Selection );
ScrollToRow( FirstVisible );
}
RefreshAll();
}
// -------------------------------------------------------------------------------- //
int guSoListBox::GetSelectedSongs( guTrackArray * tracks, const bool isdrag ) const
{
unsigned long cookie;
guSoListBox * self = wxConstCast( this, guSoListBox );
self->m_ItemsMutex.Lock();
int item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
guTrack * Track = new guTrack();
if( m_Db->GetSong( GetItemId( item ), Track ) )
{
tracks->Add( Track );
}
else
{
delete Track;
}
item = GetNextSelected( cookie );
}
self->m_ItemsMutex.Unlock();
m_MediaViewer->NormalizeTracks( tracks, isdrag );
guLogMessage( wxT( "SOListBox::GetSelectedTracks <- %li" ), tracks->Count() );
return tracks->Count();
}
// -------------------------------------------------------------------------------- //
void guSoListBox::GetAllSongs( guTrackArray * tracks )
{
m_ItemsMutex.Lock();
int count = GetItemCount();
for( int index = 0; index < count; index++ )
{
guTrack * Track = new guTrack();
if( m_Db->GetSong( GetItemId( index ), Track ) )
{
tracks->Add( Track );
}
else
{
delete Track;
}
}
m_ItemsMutex.Unlock();
}
// -------------------------------------------------------------------------------- //
wxArrayString guSoListBox::GetColumnNames( void ) const
{
return m_ColumnNames;
}
// -------------------------------------------------------------------------------- //
void AddSongsCommands( wxMenu * Menu, int SelCount )
{
wxMenu * SubMenu;
wxMenuItem * MenuItem;
if( Menu )
{
SubMenu = new wxMenu();
guConfig * Config = ( guConfig * ) guConfig::Get();
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
wxArrayString Names = Config->ReadAStr( CONFIG_KEY_COMMANDS_NAME, wxEmptyString, CONFIG_PATH_COMMANDS_NAMES );
int count = Commands.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
if( ( ( Commands[ index ].Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND ) ||
( Commands[ index ].Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND ) )
&& ( SelCount != 1 ) )
{
continue;
}
MenuItem = new wxMenuItem( Menu, ID_COMMANDS_BASE + index, Names[ index ], Commands[ index ] );
SubMenu->Append( MenuItem );
}
SubMenu->AppendSeparator();
}
else
{
MenuItem = new wxMenuItem( Menu, ID_MENU_PREFERENCES_COMMANDS, _( "Preferences" ), _( "Add commands in preferences" ) );
SubMenu->Append( MenuItem );
}
Menu->AppendSubMenu( SubMenu, _( "Commands" ) );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::AppendFastEditMenu( wxMenu * menu, const int selcount ) const
{
wxMenuItem * MenuItem;
//guLogMessage( wxT( "guSoLisBox::AppendFastEditMenu %i - %i" ), m_LastColumnRightClicked, m_LastRowRightClicked );
if( m_LastColumnRightClicked == wxNOT_FOUND || ( m_LastColumnRightClicked >= ( int ) m_Columns->Count() ) )
{
return;
}
int ColumnId = GetColumnId( m_LastColumnRightClicked );
// If its a column not editable
if( ColumnId == guSONGS_COLUMN_RATING ||
ColumnId == guSONGS_COLUMN_OFFSET ||
ColumnId == guSONGS_COLUMN_LENGTH ||
ColumnId == guSONGS_COLUMN_BITRATE ||
ColumnId == guSONGS_COLUMN_LASTPLAY ||
ColumnId == guSONGS_COLUMN_ADDEDDATE ||
ColumnId == guSONGS_COLUMN_FORMAT ||
ColumnId == guSONGS_COLUMN_FILEPATH )
return;
wxString MenuText = _( "Edit" );
MenuText += wxT( " " ) + m_ColumnNames[ ColumnId ];
MenuItem = new wxMenuItem( menu, ID_TRACKS_EDIT_COLUMN, MenuText, _( "Edit the clicked column for the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
menu->Append( MenuItem );
if( selcount > 1 )
{
MenuText = _( "Set" );
MenuText += wxT( " " ) + m_ColumnNames[ ColumnId ] + wxT( " " );
MenuText += _( "to" );
wxString ItemText = OnGetItemText( m_LastRowRightClicked, m_LastColumnRightClicked );
ItemText.Replace( wxT( "&" ), wxT( "&&" ) );
MenuText += wxT( " '" ) + ItemText + wxT( "'" );
MenuItem = new wxMenuItem( menu, ID_TRACKS_SET_COLUMN, MenuText, _( "Set the clicked column for the selected tracks" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
menu->Append( MenuItem );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::CreateContextMenu( wxMenu * Menu ) const
{
wxMenuItem * MenuItem;
int SelCount = GetSelectedCount();
int ContextMenuFlags = m_MediaViewer->GetContextMenuFlags();
MenuItem = new wxMenuItem( Menu, ID_TRACKS_PLAY,
wxString( _( "Play" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_PLAY ),
_( "Play current selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_player_tiny_light_play ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( Menu, ID_TRACKS_ENQUEUE_AFTER_ALL,
wxString( _( "Enqueue" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALL ),
_( "Add current selected songs to the playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
Menu->Append( MenuItem );
MenuItem->Enable( SelCount );
wxMenu * EnqueueMenu = new wxMenu();
MenuItem = new wxMenuItem( EnqueueMenu, ID_TRACKS_ENQUEUE_AFTER_TRACK,
wxString( _( "Current Track" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_TRACK ),
_( "Add current selected tracks to playlist after the current track" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_TRACKS_ENQUEUE_AFTER_ALBUM,
wxString( _( "Current Album" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ALBUM ),
_( "Add current selected tracks to playlist after the current album" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
MenuItem = new wxMenuItem( EnqueueMenu, ID_TRACKS_ENQUEUE_AFTER_ARTIST,
wxString( _( "Current Artist" ) ) + guAccelGetCommandKeyCodeString( ID_TRACKS_ENQUEUE_AFTER_ARTIST ),
_( "Add current selected tracks to playlist after the current artist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_add ) );
EnqueueMenu->Append( MenuItem );
MenuItem->Enable( SelCount );
Menu->Append( wxID_ANY, _( "Enqueue After" ), EnqueueMenu );
if( SelCount )
{
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_TRACKS_EDITLABELS,
wxString( _( "Edit Labels" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITLABELS ),
_( "Edit the labels assigned to the selected songs" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tags ) );
Menu->Append( MenuItem );
if( ContextMenuFlags & guCONTEXTMENU_EDIT_TRACKS )
{
MenuItem = new wxMenuItem( Menu, ID_TRACKS_EDITTRACKS,
wxString( _( "Edit Songs" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_EDITTRACKS ),
_( "Edit the songs selected" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
AppendFastEditMenu( Menu, SelCount );
wxMenu * RatingMenu = new wxMenu();
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_0,
wxT( "☆☆☆☆☆" ),
_( "Set the rating to 0" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_1,
wxT( "★☆☆☆☆" ),
_( "Set the rating to 1" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_2,
wxT( "★★☆☆☆" ),
_( "Set the rating to 2" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_3,
wxT( "★★★☆☆" ),
_( "Set the rating to 3" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_4,
wxT( "★★★★☆" ),
_( "Set the rating to 4" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
MenuItem = new wxMenuItem( RatingMenu, ID_TRACKS_SET_RATING_5,
wxT( "★★★★★" ),
_( "Set the rating to 5" ), wxITEM_NORMAL );
RatingMenu->Append( MenuItem );
Menu->AppendSubMenu( RatingMenu, _( "Set Rating" ), _( "Set the current track rating" ) );
}
Menu->AppendSeparator();
MenuItem = new wxMenuItem( Menu, ID_TRACKS_SAVETOPLAYLIST,
wxString( _( "Save to Playlist" ) ) + guAccelGetCommandKeyCodeString( ID_PLAYER_PLAYLIST_SAVE ),
_( "Save all selected tracks as a playlist" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_doc_save ) );
Menu->Append( MenuItem );
if( SelCount == 1 )
{
MenuItem = new wxMenuItem( Menu, ID_PLAYLIST_SMART_PLAYLIST, _( "Create Smart Playlist" ), _( "Create a smart playlist from this track" ) );
Menu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_PLAYER_PLAYLIST_CREATE_BESTOF, _( "Create Best Of Playlist" ), _( "Create a playlist with the best of this artist" ) );
Menu->Append( MenuItem );
}
Menu->AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_DELETEFROMLIBRARY )
{
MenuItem = new wxMenuItem( Menu, ID_TRACKS_DELETE_LIBRARY, _( "Remove from Library" ), _( "Remove the current selected tracks from library" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
}
MenuItem = new wxMenuItem( Menu, ID_TRACKS_DELETE_DRIVE, _( "Delete from Drive" ), _( "Remove the current selected tracks from drive" ) );
MenuItem->SetBitmap( guImage( guIMAGE_INDEX_tiny_edit_clear ) );
Menu->Append( MenuItem );
Menu->AppendSeparator();
wxMenu * SubMenu;
SubMenu = new wxMenu();
MenuItem = new wxMenuItem( Menu, ID_TRACKS_BROWSE_GENRE, _( "Genre" ), _( "Selects the genre of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_TRACKS_BROWSE_ARTIST, _( "Artist" ), _( "Selects the artist of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_TRACKS_BROWSE_ALBUMARTIST, _( "Album Artist" ), _( "Selects the album artist of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_TRACKS_BROWSE_COMPOSER, _( "Composer" ), _( "Selects the composer of the current song" ) );
SubMenu->Append( MenuItem );
MenuItem = new wxMenuItem( Menu, ID_TRACKS_BROWSE_ALBUM, _( "Album" ), _( "Select the album of the current song" ) );
SubMenu->Append( MenuItem );
Menu->AppendSubMenu( SubMenu, _( "Select" ), _( "Search in the library" ) );
if( ( ContextMenuFlags & guCONTEXTMENU_COPY_TO ) ||
( ContextMenuFlags & guCONTEXTMENU_LINKS ) ||
( ContextMenuFlags & guCONTEXTMENU_COMMANDS ) )
{
Menu->AppendSeparator();
if( ContextMenuFlags & guCONTEXTMENU_COPY_TO )
{
m_MediaViewer->CreateCopyToMenu( Menu );
}
if( SelCount == 1 && ( ContextMenuFlags & guCONTEXTMENU_LINKS ) )
{
AddOnlineLinksMenu( Menu );
}
if( ContextMenuFlags & guCONTEXTMENU_COMMANDS )
{
AddSongsCommands( Menu, SelCount );
}
}
}
m_MediaViewer->CreateContextMenu( Menu, guLIBRARY_ELEMENT_TRACKS );
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnSearchLinkClicked( wxCommandEvent &event )
{
unsigned long cookie;
int Item = GetFirstSelected( cookie );
if( Item != wxNOT_FOUND )
{
ExecuteOnlineLink( event.GetId(), GetSearchText( Item ) );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnCommandClicked( wxCommandEvent &event )
{
wxArrayInt Selection = GetSelectedItems();
if( Selection.Count() )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
if( Config )
{
wxArrayString Commands = Config->ReadAStr( CONFIG_KEY_COMMANDS_EXEC, wxEmptyString, CONFIG_PATH_COMMANDS_EXECS );
int CommandIndex = event.GetId() - ID_COMMANDS_BASE;
wxString CurCmd = Commands[ CommandIndex ];
if( CurCmd.Find( guCOMMAND_ALBUMPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
GetSelectedSongs( &Songs );
wxArrayInt AlbumList;
AlbumList.Add( Songs[ 0 ].m_AlbumId );
wxArrayString AlbumPaths = m_Db->GetAlbumsPaths( AlbumList );
wxString Paths = wxEmptyString;
int count = AlbumPaths.Count();
for( int index = 0; index < count; index++ )
{
AlbumPaths[ index ].Replace( wxT( " " ), wxT( "\\ " ) );
Paths += wxT( " " ) + AlbumPaths[ index ];
}
CurCmd.Replace( guCOMMAND_ALBUMPATH, Paths.Trim( false ) );
}
if( CurCmd.Find( guCOMMAND_COVERPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
GetSelectedSongs( &Songs );
wxArrayInt AlbumList;
AlbumList.Add( Songs[ 0 ].m_AlbumId );
int CoverId = m_Db->GetAlbumCoverId( AlbumList[ 0 ] );
wxString CoverPath = wxEmptyString;
if( CoverId > 0 )
{
CoverPath = wxT( "\"" ) + m_Db->GetCoverPath( CoverId ) + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_COVERPATH, CoverPath );
}
if( CurCmd.Find( guCOMMAND_TRACKPATH ) != wxNOT_FOUND )
{
guTrackArray Songs;
GetSelectedSongs( &Songs );
wxString SongList = wxEmptyString;
int count = Songs.Count();
if( count )
{
for( int index = 0; index < count; index++ )
{
SongList += wxT( " \"" ) + Songs[ index ].m_FileName + wxT( "\"" );
}
CurCmd.Replace( guCOMMAND_TRACKPATH, SongList.Trim( false ) );
}
}
//guLogMessage( wxT( "Execute Command '%s'" ), CurCmd.c_str() );
guExecute( CurCmd );
}
}
}
// -------------------------------------------------------------------------------- //
wxString guSoListBox::GetSearchText( int item ) const
{
if( item >= m_ItemsFirst && item < m_ItemsLast )
{
return wxString::Format( wxT( "\"%s\" \"%s\"" ),
m_Items[ item - m_ItemsFirst ].m_ArtistName.c_str(),
m_Items[ item - m_ItemsFirst ].m_SongName.c_str() );
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
wxString guSoListBox::GetItemName( const int row ) const
{
if( row >= m_ItemsFirst && row < m_ItemsLast )
{
return m_Items[ row - m_ItemsFirst ].m_SongName;
}
else
{
return m_Db->GetSongsName( row );
}
}
// -------------------------------------------------------------------------------- //
int guSoListBox::GetItemId( const int row ) const
{
if( row >= m_ItemsFirst && row < m_ItemsLast )
{
return m_Items[ row - m_ItemsFirst ].m_SongId;
}
else
{
return m_Db->GetSongsId( row );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnItemColumnClicked( wxListEvent &event )
{
int ColId = GetColumnId( event.m_col );
if( ColId == guSONGS_COLUMN_RATING )
{
//guLogMessage( wxT( "The rating have been clicked... %i" ), event.GetPoint().x );
int Row = event.GetInt();
Row -= m_ItemsFirst;
if( ( Row < 0 ) || ( Row >= ( int ) m_Items.Count() ) )
return;
int w = ( ( GURATING_STYLE_MID * 2 ) + GURATING_IMAGE_SIZE );
int MouseX = event.GetPoint().x;
int Rating;
if( MouseX < 3 )
Rating = 0;
else
Rating = wxMin( 5, ( wxMax( 0, MouseX - 3 ) / w ) + 1 );
if( m_Items[ Row ].m_Rating == Rating )
Rating = 0;
wxCommandEvent RatingEvent( wxEVT_MENU, ID_TRACKS_SET_RATING_0 + Rating );
AddPendingEvent( RatingEvent );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnItemColumnRClicked( wxListEvent &event )
{
m_LastColumnRightClicked = event.m_col;
m_LastRowRightClicked = event.GetInt();
//guLogMessage( wxT( "Column %i Row %i Right Clicked..." ), m_LastColumnRightClicked, event.GetInt() );
}
// -------------------------------------------------------------------------------- //
wxVariant guSoListBox::GetLastDataClicked( void )
{
guTrack * Track = &m_Items[ m_LastRowRightClicked - m_ItemsFirst ];
int ColId = GetColumnId( m_LastColumnRightClicked );
switch( ColId )
{
case guSONGS_COLUMN_NUMBER :
return wxVariant( ( long ) Track->m_Number );
case guSONGS_COLUMN_TITLE :
return wxVariant( Track->m_SongName );
case guSONGS_COLUMN_ARTIST :
return wxVariant( Track->m_ArtistName );
case guSONGS_COLUMN_ALBUMARTIST :
return wxVariant( Track->m_AlbumArtist );
case guSONGS_COLUMN_ALBUM :
return wxVariant( Track->m_AlbumName );
case guSONGS_COLUMN_GENRE :
return wxVariant( Track->m_GenreName );
case guSONGS_COLUMN_COMPOSER :
return wxVariant( Track->m_Composer );
case guSONGS_COLUMN_DISK :
return wxVariant( Track->m_Disk );
case guSONGS_COLUMN_YEAR :
return wxVariant( ( long ) Track->m_Year );
}
return wxVariant();
}
// -------------------------------------------------------------------------------- //
void guSoListBox::UpdatedTracks( const guTrackArray * tracks )
{
int ItemIndex;
int ItemCount = m_Items.Count();
bool ClearSelection = false;
if( !ItemCount )
return;
int TrackIndex;
int TrackCount = tracks->Count();
for( TrackIndex = 0; TrackIndex < TrackCount; TrackIndex++ )
{
guTrack &CurTrack = tracks->Item( TrackIndex );
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
if( ( ( CurTrack.m_SongId == m_Items[ ItemIndex ].m_SongId ) &&
( ( CurTrack.m_Type == guTRACK_TYPE_JAMENDO ) || ( CurTrack.m_Type == guTRACK_TYPE_MAGNATUNE ) ) ) ||
( CurTrack.m_FileName == m_Items[ ItemIndex ].m_FileName ) )
{
m_Items[ ItemIndex ] = CurTrack;
RefreshRow( ItemIndex + m_ItemsFirst );
if( !ClearSelection )
ClearSelection = true;
}
}
}
if( ClearSelection )
ClearSelectedItems();
}
// -------------------------------------------------------------------------------- //
void guSoListBox::UpdatedTrack( const guTrack * track )
{
int ItemIndex;
int ItemCount = m_Items.Count();
if( !ItemCount )
return;
for( ItemIndex = 0; ItemIndex < ItemCount; ItemIndex++ )
{
if( track->m_FileName == m_Items[ ItemIndex ].m_FileName )
{
m_Items[ ItemIndex ] = * track;
RefreshRow( ItemIndex );
}
}
}
// -------------------------------------------------------------------------------- //
int guSoListBox::FindItem( const int trackid )
{
int Count = m_Items.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items[ Index ].m_SongId == trackid )
{
return Index;
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guSoListBox::SetTracksOrder( const int order )
{
if( m_TracksOrder != order )
{
m_TracksOrder = order;
m_Db->SetTracksOrder( m_TracksOrder );
}
else
{
m_TracksOrderDesc = !m_TracksOrderDesc;
m_Db->SetTracksOrderDesc( m_TracksOrderDesc );
}
int ColId = m_TracksOrder;
// Create the Columns
int CurColId;
int Count = m_ColumnNames.Count();
for( int Index = 0; Index < Count; Index++ )
{
CurColId = GetColumnId( Index );
SetColumnLabel( Index,
m_ColumnNames[ CurColId ] + ( ( ColId == CurColId ) ? ( m_TracksOrderDesc ? wxT( " ▼" ) : wxT( " ▲" ) ) : wxEmptyString ) );
}
ReloadItems();
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnCreateSmartPlaylist( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedSongs( &Tracks );
if( Tracks.Count() == 1 )
{
m_MediaViewer->CreateSmartPlaylist( Tracks[ 0 ].m_ArtistName, Tracks[ 0 ].m_SongName );
}
}
// -------------------------------------------------------------------------------- //
void guSoListBox::OnCreateBestOfPlaylist( wxCommandEvent &event )
{
guTrackArray Tracks;
GetSelectedSongs( &Tracks );
if( !Tracks.IsEmpty() )
{
const guTrack &Track = Tracks[ 0 ];
if( Track.m_MediaViewer )
m_MediaViewer->CreateBestOfPlaylist( Track );
}
}
}
// -------------------------------------------------------------------------------- //
| 36,732
|
C++
|
.cpp
| 844
| 34.872038
| 167
| 0.545225
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,626
|
StatusBar.cpp
|
anonbeat_guayadeque/src/ui/statusbar/StatusBar.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "StatusBar.h"
#include "AuiNotebook.h"
#include "EventCommandIds.h"
#include "Images.h"
#include "Preferences.h"
#include "MainFrame.h"
#include "Utils.h"
namespace Guayadeque {
#define guAUDIOSCROBBLE_PANEL_SIZE 40
enum guStatusBarClickAction {
guSTATUSBAR_CLICK_ACTION_NONE = -1,
guSTATUSBAR_CLICK_ACTION_AUDIOSCROBBLE
};
#define guSTATUSBAR_CLICK_TIMEOUT 250
// -------------------------------------------------------------------------------- //
// guGauge
// -------------------------------------------------------------------------------- //
BEGIN_EVENT_TABLE(guGauge, wxControl)
EVT_PAINT (guGauge::OnPaint)
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guGauge::guGauge( wxWindow * parent, const wxString &label, bool showporcent,
wxWindowID id, unsigned int max, const wxPoint &pos, const wxSize &size, long style ) :
wxControl( parent, id, pos, size, style )
{
m_LastValue = wxNOT_FOUND;
m_ShowPorcent = showporcent;
m_PaintWidth = 0;
//m_Value = 0;
//m_Range = max;
m_Label = label;
m_Font = wxSystemSettings::GetFont( wxSYS_DEVICE_DEFAULT_FONT );
m_FgColor1 = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
m_FgColor2 = wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT );
m_GradStart = wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT );
m_GradEnd = wxSystemSettings::GetColour( wxSYS_COLOUR_HOTLIGHT );
SetRange( max );
SetValue( 0 );
}
// -------------------------------------------------------------------------------- //
guGauge::~guGauge()
{
}
// -------------------------------------------------------------------------------- //
void guGauge::OnPaint( wxPaintEvent &event )
{
//guLogMessage( wxT( "Gauge::OnPaint" ) );
wxSize s = GetSize();
wxPaintDC dc( this );
dc.SetFont( m_Font );
dc.SetPen( * wxTRANSPARENT_PEN );
dc.SetBrush( * wxTRANSPARENT_BRUSH );
dc.DrawRectangle( 1, 1, s.x, s.y );
dc.SetTextForeground( m_FgColor1 );
wxString LabelStr;
if( m_ShowPorcent )
{
LabelStr = m_Label + wxString::Format( wxT( " %u%%" ), ( ( m_PaintWidth * 100 ) / s.x ) );
}
else
{
LabelStr = m_Label + wxString::Format( wxT( " %i / %i" ), m_Value, m_Range );
}
dc.DrawText( LabelStr, 4, 2 );
if( m_PaintWidth )
{
wxRect rect;
rect.x = 1;
rect.y = 1;
rect.width = m_PaintWidth;
rect.height = s.y;
wxDCClipper clip( dc, rect );
//dc.DrawRectangle( 1, 1, ( long ) m_Value, s.y );
rect.width = s.x;
dc.GradientFillLinear( rect, m_GradStart, m_GradEnd, wxEAST );
dc.SetTextForeground( m_FgColor2 );
dc.DrawText( LabelStr, 4, 2 );
}
}
// -------------------------------------------------------------------------------- //
bool guGauge::SetValue( int value )
{
//guLogMessage( wxT( "Value: %u (%f) of %u -> %u%%" ), value, m_LastValue, m_Range, (value * 100) / m_Range );
m_Value = value;
m_PaintWidth = value * m_Factor;
if( m_LastValue != m_PaintWidth )
{
m_LastValue = m_PaintWidth;
Refresh();
// Update();
}
return true;
}
// -------------------------------------------------------------------------------- //
void guGauge::SetRange( int range )
{
//guLogMessage( wxT( "Range: %u" ), range );
m_Range = range;
m_Factor = (float) GetSize().x / (float) range;
SetValue( GetValue() );
Refresh();
// Update();
}
// -------------------------------------------------------------------------------- //
// guStatusBar
// -------------------------------------------------------------------------------- //
guStatusBar::guStatusBar( wxWindow * parent ) :
wxStatusBar( parent, wxID_ANY, wxST_SIZEGRIP | wxSB_FLAT )
{
m_LastClickAction = guSTATUSBAR_CLICK_ACTION_NONE;
m_ASBitmap = new wxStaticBitmap( this, wxID_ANY, guImage( guIMAGE_INDEX_lastfm_as_off ) );
m_ASBitmap->SetToolTip( _( "Enable audioscrobbling" ) );
m_SelInfo = new wxStaticText( this, wxID_ANY, wxEmptyString );
m_SelInfo->SetToolTip( _( "Shows information about the selected items" ) );
m_ClickTimer.SetOwner( this );
Bind( wxEVT_SIZE, &guStatusBar::OnSize, this );
m_ASBitmap->Bind( wxEVT_LEFT_DOWN, &guStatusBar::OnButtonClick, this );
m_ASBitmap->Bind( wxEVT_LEFT_DCLICK, &guStatusBar::OnButtonDClick, this );
Bind( wxEVT_TIMER, &guStatusBar::OnTimerEvent, this );
SetSizes( 2 );
}
// -------------------------------------------------------------------------------- //
guStatusBar::~guStatusBar()
{
Unbind( wxEVT_SIZE, &guStatusBar::OnSize, this );
m_ASBitmap->Unbind( wxEVT_LEFT_DOWN, &guStatusBar::OnButtonClick, this );
m_ASBitmap->Unbind( wxEVT_LEFT_DCLICK, &guStatusBar::OnButtonDClick, this );
Unbind( wxEVT_TIMER, &guStatusBar::OnTimerEvent, this );
if( m_ASBitmap )
delete m_ASBitmap;
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnSize( wxSizeEvent &event )
{
wxRect rect;
UpdateGauges();
//
if( m_ASBitmap )
{
//size = ASBitmap->GetSize();
GetFieldRect( GetFieldsCount() - 1, rect );
m_ASBitmap->Move( rect.x + 1, rect.y + 2 );
}
if( m_SelInfo )
{
GetFieldRect( GetFieldsCount() - 2, rect );
m_SelInfo->Move( rect.x + 1, rect.y + 3 );
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guStatusBar::UpdateAudioScrobbleIcon( bool Enabled )
{
if( m_ASBitmap )
{
m_ASBitmap->SetBitmap( guImage( Enabled ? guIMAGE_INDEX_lastfm_as_on : guIMAGE_INDEX_lastfm_as_off ) );
m_ASBitmap->SetToolTip( Enabled ? _( "Disable audioscrobbling" ) : _( "Enable audioscrobbling" ) );
m_ASBitmap->Refresh();
}
}
// -------------------------------------------------------------------------------- //
void guStatusBar::SetAudioScrobble( const bool audioscrobble )
{
OnAudioScrobbleClicked();
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnButtonClick( wxMouseEvent &event )
{
//guLogMessage( wxT( "OnButtonClick") );
m_LastClickAction = guSTATUSBAR_CLICK_ACTION_NONE;
if( event.GetEventObject() == m_ASBitmap )
{
m_LastClickAction = guSTATUSBAR_CLICK_ACTION_AUDIOSCROBBLE;
}
if( m_ClickTimer.IsRunning() )
m_ClickTimer.Stop();
m_ClickTimer.Start( guSTATUSBAR_CLICK_TIMEOUT, wxTIMER_ONE_SHOT );
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnButtonDClick( wxMouseEvent &event )
{
if( m_ClickTimer.IsRunning() )
m_ClickTimer.Stop();
if( event.GetEventObject() == m_ASBitmap )
{
OnAudioScrobbleDClicked();
}
m_LastClickAction = guSTATUSBAR_CLICK_ACTION_NONE;
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnTimerEvent( wxTimerEvent &event )
{
if( m_LastClickAction == guSTATUSBAR_CLICK_ACTION_AUDIOSCROBBLE )
OnAudioScrobbleClicked();
m_LastClickAction = guSTATUSBAR_CLICK_ACTION_NONE;
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnAudioScrobbleClicked( void )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
bool ConfigUpdated = false;
int LastFMEnabled = wxNOT_FOUND;
int LibreFMEnabled = wxNOT_FOUND;
if( !Config->ReadStr( CONFIG_KEY_LASTFM_USERNAME, wxEmptyString, CONFIG_PATH_LASTFM ).IsEmpty() &&
!Config->ReadStr( CONFIG_KEY_LASTFM_PASSWORD, wxEmptyString, CONFIG_PATH_LASTFM ).IsEmpty() )
{
LastFMEnabled = !Config->ReadBool( CONFIG_KEY_LASTFM_ENABLED, false, CONFIG_PATH_LASTFM );
Config->WriteBool( CONFIG_KEY_LASTFM_ENABLED, LastFMEnabled, CONFIG_PATH_LASTFM );
ConfigUpdated = true;
}
if( ( ( LastFMEnabled == ( LibreFMEnabled = !Config->ReadBool( CONFIG_KEY_LIBREFM_ENABLED, false, CONFIG_PATH_LIBREFM ) ) ) ||
( LastFMEnabled == wxNOT_FOUND ) ) &&
!Config->ReadStr( CONFIG_KEY_LIBREFM_USERNAME, wxEmptyString, CONFIG_PATH_LIBREFM ).IsEmpty() &&
!Config->ReadStr( CONFIG_KEY_LIBREFM_PASSWORD, wxEmptyString, CONFIG_PATH_LIBREFM ).IsEmpty() )
{
Config->WriteBool( CONFIG_KEY_LIBREFM_ENABLED, LibreFMEnabled, CONFIG_PATH_LIBREFM );
}
if( ConfigUpdated )
{
Config->Flush();
Config->SendConfigChangedEvent( guPREFERENCE_PAGE_FLAG_AUDIOSCROBBLE );
UpdateAudioScrobbleIcon( ( ( LastFMEnabled != wxNOT_FOUND ) && LastFMEnabled ) || LibreFMEnabled );
}
}
// -------------------------------------------------------------------------------- //
void guStatusBar::OnAudioScrobbleDClicked( void )
{
//guLogMessage( wxT( "AUdioScrobble clicked..." ) );
wxCommandEvent CmdEvent( wxEVT_MENU, ID_MENU_PREFERENCES );
CmdEvent.SetInt( guPREFERENCE_PAGE_AUDIOSCROBBLE );
wxPostEvent( guMainFrame::GetMainFrame(), CmdEvent );
}
// -------------------------------------------------------------------------------- //
void guStatusBar::SetSizes( int FieldCnt )
{
int * FieldWidths = ( int * ) malloc( sizeof( int ) * FieldCnt );
if( FieldWidths )
{
for( int index = 0; index < FieldCnt; index++ )
{
if( index == 0 )
FieldWidths[ index ] = -1;
else if( index == ( FieldCnt - 1 ) )
FieldWidths[ index ] = guAUDIOSCROBBLE_PANEL_SIZE;
else if( ( index == ( FieldCnt - 2 ) ) && !m_SelInfo->GetLabel().IsEmpty() )
{
int Width;
int Height;
GetTextExtent( m_SelInfo->GetLabel(), &Width, &Height );
FieldWidths[ index ] = Width + 10;
}
else
FieldWidths[ index ] = 200;
//printf( "Width: %i\n", FieldWidths[ index ] );
}
//SetStatusWidths( FieldCnt, FieldWidths );
SetFieldsCount( FieldCnt, FieldWidths );
free( FieldWidths );
//Refresh();
}
//int FieldStyles[] = { wxSB_FLAT, wxSB_FLAT, wxSB_FLAT };
//SetStatusStyles( 3, FieldStyles );
}
// -------------------------------------------------------------------------------- //
void guStatusBar::UpdateGauges( void )
{
wxRect rect;
wxSize size;
int PanelIndex = 0;
// Update the pos for all the gauges in the statusbar
int count = m_Gauges.Count();
for( int index = 0; index < count; index++ )
{
if( m_Gauges[ index ] )
{
// The first Panel is the info with index 0, the first gauge will be 1
PanelIndex++;
GetFieldRect( PanelIndex, rect );
size.x = rect.width - 2;
size.y = rect.height - 2;
m_Gauges[ index ]->Move( rect.x + 1, rect.y + 1 );
m_Gauges[ index ]->SetSize( size );
}
}
Refresh();
}
// -------------------------------------------------------------------------------- //
int guStatusBar::AddGauge( const wxString &text, bool showporcent )
{
m_Gauges.Add( new guGauge( this, text, showporcent ) );
SetSizes( GetFieldsCount() + 1 );
UpdateGauges();
return ( m_Gauges.Count() - 1 );
}
// -------------------------------------------------------------------------------- //
int guStatusBar::RemoveGauge( int gaugeid )
{
SetSizes( GetFieldsCount() - 1 );
RemoveChild( m_Gauges[ gaugeid ] );
delete m_Gauges[ gaugeid ];
m_Gauges[ gaugeid ] = NULL;
//Gauges.RemoveAt( gaugeid );
// if( gaugeid == ( Gauges.Count() - 1 )
// {
// Gauges.RemoveAt( gaugeid );
// }
// We remove all empty gauges from the array from the end
// so the valid index dont get changed when remove a lower gauge index
while( m_Gauges.Count() && ( m_Gauges[ m_Gauges.Count() - 1 ] == NULL ) )
{
m_Gauges.RemoveAt( m_Gauges.Count() - 1 );
}
UpdateGauges();
return m_Gauges.Count();
}
// -------------------------------------------------------------------------------- //
void guStatusBar::SetSelInfo( const wxString &label )
{
bool PrevState = !m_SelInfo->GetLabel().IsEmpty();
bool NextState = !label.IsEmpty();
m_SelInfo->SetLabel( label );
int FieldCount = GetFieldsCount();
if( PrevState != NextState )
{
if( NextState )
{
FieldCount++;
}
else
{
FieldCount--;
}
}
SetSizes( FieldCount );
if( NextState )
{
wxRect rect;
GetFieldRect( GetFieldsCount() - 2, rect );
m_SelInfo->Move( rect.x + 1, rect.y + 3 );
}
UpdateGauges();
}
// -------------------------------------------------------------------------------- //
void guStatusBar::DrawField( wxDC &dc, int i, int textHeight )
{
wxRect rect;
GetFieldRect( i, rect );
if( i < ( GetFieldsCount() - 1 ) )
{
dc.SetPen( m_mediumShadowPen );
dc.DrawLine( rect.x + rect.width, rect.y + 1, rect.x + rect.width, rect.y + rect.height - 1 );
//dc.SetPen( m_hilightPen );
//dc.DrawLine( rect.x + rect.width, rect.y + 1, rect.x + rect.width, rect.y + rect.height - 1 );
}
DrawFieldText( dc, rect, i, textHeight );
}
}
// -------------------------------------------------------------------------------- //
| 14,610
|
C++
|
.cpp
| 379
| 33.496042
| 130
| 0.529915
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,627
|
AuiManagedPanel.cpp
|
anonbeat_guayadeque/src/ui/aui/AuiManagedPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AuiManagedPanel.h"
#include "Utils.h"
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guAuiManagedPanel::guAuiManagedPanel( wxWindow * parent, wxAuiManager * manager ) :
wxPanel( parent, wxID_ANY, wxDefaultPosition, wxSize( -1, -1 ), wxTAB_TRAVERSAL|wxNO_BORDER )
{
m_Manager = manager;
Bind( wxEVT_SIZE, &guAuiManagedPanel::OnChangedSize, this );
}
// -------------------------------------------------------------------------------- //
guAuiManagedPanel::~guAuiManagedPanel()
{
Unbind( wxEVT_SIZE, &guAuiManagedPanel::OnChangedSize, this );
}
// -------------------------------------------------------------------------------- //
void guAuiManagedPanel::OnChangedSize( wxSizeEvent &event )
{
wxSize Size = event.GetSize();
wxAuiPaneInfo &PaneInfo = m_Manager->GetPane( this );
if( PaneInfo.IsOk() )
{
if( ( PaneInfo.floating_size.x != Size.x ) || ( PaneInfo.floating_size.y != Size.y ) )
{
PaneInfo.floating_size.x = Size.x;
PaneInfo.floating_size.y = Size.y;
}
}
event.Skip();
}
}
// -------------------------------------------------------------------------------- //
| 2,285
|
C++
|
.cpp
| 53
| 40.264151
| 97
| 0.536454
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,628
|
AuiManagerPanel.cpp
|
anonbeat_guayadeque/src/ui/aui/AuiManagerPanel.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AuiManagerPanel.h"
#include "AuiDockArt.h"
#include "AuiNotebook.h"
#include "EventCommandIds.h"
#include "MainFrame.h"
#include "Settings.h"
#include "Utils.h"
#include <wx/settings.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guAuiManagerPanel::guAuiManagerPanel( wxWindow * parent ) :
wxPanel( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER )
{
m_MenuBar = NULL;
m_AuiManager.SetManagedWindow( this );
m_AuiManager.SetArtProvider( new guAuiDockArt() );
m_AuiManager.SetFlags( wxAUI_MGR_ALLOW_FLOATING |
wxAUI_MGR_TRANSPARENT_DRAG |
wxAUI_MGR_TRANSPARENT_HINT );
wxAuiDockArt * AuiDockArt = m_AuiManager.GetArtProvider();
wxColour BaseColor = guCOLOR_BASE;
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_GRADIENT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_SASH_COLOUR, guCOLOR_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_CAPTION_SIZE, guSIZE_CAPTION );
AuiDockArt->SetMetric( wxAUI_DOCKART_PANE_BORDER_SIZE, guSIZE_BORDER );
AuiDockArt->SetMetric( wxAUI_DOCKART_SASH_SIZE, guSIZE_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_GRADIENT_TYPE, guGRADIENT_TYPE );
m_AuiManager.Bind( wxEVT_AUI_PANE_CLOSE, &guAuiManagerPanel::OnPaneClose, this );
}
// -------------------------------------------------------------------------------- //
guAuiManagerPanel::~guAuiManagerPanel()
{
m_AuiManager.Unbind( wxEVT_AUI_PANE_CLOSE, &guAuiManagerPanel::OnPaneClose, this );
m_AuiManager.UnInit();
}
// -------------------------------------------------------------------------------- //
void guAuiManagerPanel::ShowPanel( const int panelid, bool show )
{
int PanelIndex = m_PanelIds.Index( panelid );
if( PanelIndex != wxNOT_FOUND )
{
wxString PaneName = m_PanelNames[ PanelIndex ];
wxAuiPaneInfo &PaneInfo = m_AuiManager.GetPane( PaneName );
if( PaneInfo.IsOk() )
{
if( show )
PaneInfo.Show();
else
PaneInfo.Hide();
m_AuiManager.Update();
}
if( show )
m_VisiblePanels |= panelid;
else
m_VisiblePanels ^= panelid;
if( !m_MenuBar )
{
guMainFrame * MainFrame = ( guMainFrame * ) guMainFrame::GetMainFrame();
m_MenuBar = MainFrame->GetMenuBar();
}
if( m_MenuBar )
{
wxMenuItem * MenuItem = m_MenuBar->FindItem( m_PanelCmdIds[ PanelIndex ] );
if( MenuItem )
{
MenuItem->Check( show );
}
}
guLogMessage( wxT( "Id: %i Pane: %s Show:%i Flags:%08X" ), panelid, PaneName.c_str(), show, m_VisiblePanels );
}
}
// -------------------------------------------------------------------------------- //
void guAuiManagerPanel::OnPaneClose( wxAuiManagerEvent &event )
{
wxAuiPaneInfo * PaneInfo = event.GetPane();
int PanelIndex = m_PanelNames.Index( PaneInfo->name );
if( PanelIndex != wxNOT_FOUND )
{
guLogMessage( wxT( "OnPaneClose: %s %i" ), m_PanelNames[ PanelIndex ].c_str(), m_PanelCmdIds[ PanelIndex ] );
ShowPanel( m_PanelIds[ PanelIndex ], false );
}
event.Veto();
}
// -------------------------------------------------------------------------------- //
void guAuiManagerPanel::LoadPerspective( const wxString &layoutstr, const unsigned int visiblepanels )
{
int Count = m_PanelIds.Count();
for( int Index = 0; Index < Count; Index++ )
{
int PanelId = m_PanelIds[ Index ];
if( ( visiblepanels & PanelId ) != ( m_VisiblePanels & PanelId ) )
{
ShowPanel( PanelId, ( visiblepanels & PanelId ) );
}
}
m_AuiManager.LoadPerspective( layoutstr, true );
}
// -------------------------------------------------------------------------------- //
void guAuiManagerPanel::SaveLayout( wxXmlNode * xmlnode, const wxString &name )
{
wxXmlNode * XmlNode = new wxXmlNode( wxXML_ELEMENT_NODE, name );
wxXmlAttribute * Property = new wxXmlAttribute( wxT( "panels" ), wxString::Format( wxT( "%d" ), VisiblePanels() ),
new wxXmlAttribute( wxT( "layout" ), SavePerspective(),
NULL ) );
XmlNode->SetAttributes( Property );
wxXmlNode * Columns = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "columns" ) );
int Count = GetListViewColumnCount();
for( int Index = 0; Index < Count; Index++ )
{
int ColumnPos;
int ColumnWidth;
bool ColumnEnabled;
wxXmlNode * Column = new wxXmlNode( wxXML_ELEMENT_NODE, wxT( "column" ) );
GetListViewColumnData( Index, &ColumnPos, &ColumnWidth, &ColumnEnabled );
Property = new wxXmlAttribute( wxT( "id" ), wxString::Format( wxT( "%d" ), Index ),
new wxXmlAttribute( wxT( "pos" ), wxString::Format( wxT( "%d" ), ColumnPos ),
new wxXmlAttribute( wxT( "width" ), wxString::Format( wxT( "%d" ), ColumnWidth ),
new wxXmlAttribute( wxT( "enabled" ), wxString::Format( wxT( "%d" ), ColumnEnabled ),
NULL ) ) ) );
Column->SetAttributes( Property );
Columns->AddChild( Column );
}
XmlNode->AddChild( Columns );
xmlnode->AddChild( XmlNode );
}
// -------------------------------------------------------------------------------- //
void guAuiManagerPanel::LoadLayout( wxXmlNode * xmlnode )
{
wxString Field;
long VisiblePanels;
wxString LayoutStr;
xmlnode->GetAttribute( wxT( "panels" ), &Field );
Field.ToLong( &VisiblePanels );
xmlnode->GetAttribute( wxT( "layout" ), &LayoutStr );
wxXmlNode * Columns = xmlnode->GetChildren();
if( Columns && ( Columns->GetName() == wxT( "columns" ) ) )
{
wxXmlNode * Column = Columns->GetChildren();
while( Column && ( Column->GetName() == wxT( "column" ) ) )
{
long ColumnId;
long ColumnPos;
long ColumnWidth;
long ColumnEnabled;
Column->GetAttribute( wxT( "id" ), &Field );
Field.ToLong( &ColumnId );
Column->GetAttribute( wxT( "pos" ), &Field );
Field.ToLong( &ColumnPos );
Column->GetAttribute( wxT( "width" ), &Field );
Field.ToLong( &ColumnWidth );
Column->GetAttribute( wxT( "enabled" ), &Field );
Field.ToLong( &ColumnEnabled );
SetListViewColumnData( ColumnId, ColumnPos, ColumnWidth, ColumnEnabled );
Column = Column->GetNext();
}
}
LoadPerspective( LayoutStr, VisiblePanels );
}
}
// -------------------------------------------------------------------------------- //
| 8,544
|
C++
|
.cpp
| 186
| 39.322581
| 119
| 0.567925
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,629
|
AuiDockArt.cpp
|
anonbeat_guayadeque/src/ui/aui/AuiDockArt.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AuiDockArt.h"
#include "Images.h"
#include "Utils.h"
namespace Guayadeque {
wxString wxAuiChopText(wxDC& dc, const wxString& text, int max_size)
{
wxCoord x,y;
// first check if the text fits with no problems
dc.GetTextExtent(text, &x, &y);
if (x <= max_size)
return text;
size_t i, len = text.Length();
size_t last_good_length = 0;
for (i = 0; i < len; ++i)
{
wxString s = text.Left(i);
s += wxT("...");
dc.GetTextExtent(s, &x, &y);
if (x > max_size)
break;
last_good_length = i;
}
wxString ret = text.Left(last_good_length);
ret += wxT("...");
return ret;
}
// -------------------------------------------------------------------------------- //
guAuiDockArt::guAuiDockArt() : wxAuiDefaultDockArt()
{
m_CloseNormal = guImage( guIMAGE_INDEX_tiny_close_normal );
m_CloseHighLight = guImage( guIMAGE_INDEX_tiny_close_highlight );
}
// -------------------------------------------------------------------------------- //
void inline DrawGradientRectangle( wxDC &dc, const wxRect &rect, const wxColour &start_color, const wxColour &end_color, int direction )
{
dc.GradientFillLinear( rect, start_color, end_color, direction == wxAUI_GRADIENT_VERTICAL ? wxNORTH : wxWEST );
}
// -------------------------------------------------------------------------------- //
void guAuiDockArt::DrawCaptionBackground( wxDC &dc, const wxRect &rect, bool active )
{
if( m_gradientType == wxAUI_GRADIENT_NONE )
{
if( active )
dc.SetBrush( wxBrush( m_activeCaptionColour ) );
else
dc.SetBrush( wxBrush( m_inactiveCaptionColour ) );
dc.DrawRectangle( rect.x, rect.y, rect.width, rect.height );
}
else
{
if( active )
{
// on mac the gradients are expected to become darker from the top
#ifdef __WXMAC__
DrawGradientRectangle( dc, rect,
m_activeCaptionColour,
m_activeCaptionGradientColour,
m_gradientType );
#else
// on other platforms, active gradients become lighter at the top
DrawGradientRectangle( dc, rect,
m_activeCaptionColour,
m_activeCaptionGradientColour,
m_gradientType );
#endif
}
else
{
#ifdef __WXMAC__
// on mac the gradients are expected to become darker from the top
DrawGradientRectangle( dc, rect,
m_inactiveCaptionColour,
m_inactiveCaptionGradientColour,
m_gradientType );
#else
// on other platforms, inactive gradients become lighter at the bottom
DrawGradientRectangle( dc, rect,
m_inactiveCaptionColour,
m_inactiveCaptionGradientColour,
m_gradientType );
#endif
}
}
dc.SetPen( m_borderPen );
int y = rect.y + rect.height - 1;
dc.DrawLine( rect.x, y, rect.x + rect.width, y );
}
// -------------------------------------------------------------------------------- //
void guAuiDockArt::DrawCaption( wxDC &dc, wxWindow * window, const wxString &text, const wxRect &rect, wxAuiPaneInfo &pane )
{
dc.SetPen( * wxTRANSPARENT_PEN );
dc.SetFont( m_captionFont );
DrawCaptionBackground( dc, rect, bool( pane.state & wxAuiPaneInfo::optionActive ) );
dc.SetTextForeground( pane.state & wxAuiPaneInfo::optionActive ? m_activeCaptionTextColour : m_inactiveCaptionTextColour );
wxCoord w, h;
dc.GetTextExtent( wxT( "ABCDEFHXfgkj" ), &w, &h );
wxRect clip_rect = rect;
clip_rect.width -= 3; // text offset
clip_rect.width -= 2; // button padding
if( pane.HasCloseButton() )
clip_rect.width -= m_buttonSize;
if( pane.HasPinButton() )
clip_rect.width -= m_buttonSize;
if( pane.HasMaximizeButton() )
clip_rect.width -= m_buttonSize;
wxString draw_text = wxAuiChopText( dc, text, clip_rect.width );
dc.SetClippingRegion( clip_rect );
dc.DrawText( draw_text, rect.x + 3, rect.y + ( rect.height / 2 ) - ( h / 2 ) - 1 );
dc.DestroyClippingRegion();
}
// -------------------------------------------------------------------------------- //
void guAuiDockArt::DrawPaneButton( wxDC &dc, wxWindow * window, int button, int button_state,
const wxRect &rect, wxAuiPaneInfo &pane )
{
if( button == wxAUI_BUTTON_CLOSE )
{
int Offset = 0;
if( ( button_state & wxAUI_BUTTON_STATE_PRESSED ) )
Offset++;
dc.DrawBitmap( ( ( button_state & ( wxAUI_BUTTON_STATE_HOVER | wxAUI_BUTTON_STATE_PRESSED ) ) ? m_CloseHighLight : m_CloseNormal ),
rect.x + Offset, rect.y + 2 + Offset, true );
return;
}
wxAuiDefaultDockArt::DrawPaneButton( dc, window, button, button_state, rect, pane );
}
}
// -------------------------------------------------------------------------------- //
| 6,236
|
C++
|
.cpp
| 148
| 34.72973
| 139
| 0.547014
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,630
|
AuiNotebook.cpp
|
anonbeat_guayadeque/src/ui/aui/AuiNotebook.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AuiNotebook.h"
#include "Images.h"
#include "Settings.h"
#include "Utils.h"
#include <wx/dc.h>
namespace Guayadeque {
#define guAUI_TAB_HEIGHT 28
// -------------------------------------------------------------------------------- //
unsigned char wxAuiBlendColour( unsigned char fg, unsigned char bg, double alpha )
{
double result = bg + ( alpha * ( fg - bg ) );
if( result < 0.0 )
result = 0.0;
if( result > 255 )
result = 255;
return ( unsigned char ) result;
}
// -------------------------------------------------------------------------------- //
wxColour wxAuiStepColour( const wxColour &c, int ialpha )
{
if( c == wxNullColour )
return c;
unsigned char r = c.Red();
unsigned char g = c.Green();
unsigned char b = c.Blue();
unsigned char bg;
// ialpha is 0..200 where 0 is completely black
// and 200 is completely white and 100 is the same
// convert that to normal alpha 0.0 - 1.0
ialpha = wxMin( ialpha, 200 );
ialpha = wxMax( ialpha, 0 );
double alpha = ( ( double ) ( ialpha - 100.0 ) ) / 100.0;
if( ialpha > 100 )
{
// blend with white
bg = 255;
alpha = 1.0 - alpha; // 0 = transparent fg; 1 = opaque fg
}
else
{
// blend with black
bg = 0;
alpha += 1.0; // 0 = transparent fg; 1 = opaque fg
}
r = wxAuiBlendColour( r, bg, alpha );
g = wxAuiBlendColour( g, bg, alpha );
b = wxAuiBlendColour( b, bg, alpha );
return wxColour( r, g, b );
}
// -------------------------------------------------------------------------------- //
static void inline IndentPressedBitmap( wxRect * rect, int button_state )
{
if( button_state == wxAUI_BUTTON_STATE_PRESSED )
{
rect->x++;
rect->y++;
}
}
// -------------------------------------------------------------------------------- //
// guAuiTabArt
// -------------------------------------------------------------------------------- //
guAuiTabArt::guAuiTabArt() : wxAuiDefaultTabArt()
{
m_BgColor = wxSystemSettings::GetColour( wxSYS_COLOUR_BACKGROUND );
m_SelBgColor = wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT );
m_TextFgColor = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
m_SelTextFgColour = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
m_disabledCloseBmp = guImage( guIMAGE_INDEX_tiny_close_normal );
m_activeCloseBmp = guImage( guIMAGE_INDEX_tiny_close_highlight );
}
// -------------------------------------------------------------------------------- //
guAuiTabArt::~guAuiTabArt()
{
}
// -------------------------------------------------------------------------------- //
wxAuiTabArt * guAuiTabArt::Clone()
{
return new guAuiTabArt( *this );
}
// -------------------------------------------------------------------------------- //
void guAuiTabArt::DrawBackground( wxDC &dc, wxWindow * wnd, const wxRect &rect )
{
// draw background
//wxColour top_color = m_base_colour;
wxColour top_color = m_BgColor;
wxColour bottom_color = m_BgColor; //wxAuiStepColour( m_baseColour, 120 );
wxRect r;
if( m_flags & wxAUI_NB_BOTTOM )
r = wxRect( rect.x, rect.y, rect.width + 2, rect.height );
// TODO: else if (m_flags &wxAUI_NB_LEFT) {}
// TODO: else if (m_flags &wxAUI_NB_RIGHT) {}
else //for wxAUI_NB_TOP
r = wxRect( rect.x, rect.y, rect.width + 2, rect.height - 3 );
dc.GradientFillLinear( r, top_color, bottom_color, wxNORTH );
// draw base lines
dc.SetPen( m_borderPen );
int y = rect.GetHeight();
int w = rect.GetWidth();
if( m_flags & wxAUI_NB_BOTTOM )
{
dc.SetBrush( wxBrush( bottom_color ) );
dc.DrawRectangle( -1, 0, w + 2, 4 );
}
// TODO: else if (m_flags &wxAUI_NB_LEFT) {}
// TODO: else if (m_flags &wxAUI_NB_RIGHT) {}
else //for wxAUI_NB_TOP
{
dc.SetBrush( wxBrush( top_color ) );
dc.DrawRectangle( -1, y - 4, w + 2, 5 );
}
}
// -------------------------------------------------------------------------------- //
void guAuiTabArt::DrawTab(wxDC &dc, wxWindow * wnd, const wxAuiNotebookPage &page,
const wxRect & in_rect, int close_button_state, wxRect * out_tab_rect,
wxRect * out_button_rect, int * x_extent )
{
wxCoord normal_textx, normal_texty;
wxCoord selected_textx, selected_texty;
wxCoord texty;
// if the caption is empty, measure some temporary text
wxString caption = page.caption;
if( caption.empty() )
caption = wxT("Xj");
dc.SetFont(m_selectedFont);
dc.GetTextExtent(caption, &selected_textx, &selected_texty);
dc.SetFont(m_normalFont);
dc.GetTextExtent(caption, &normal_textx, &normal_texty);
// figure out the size of the tab
wxSize tab_size = GetTabSize(dc,
wnd,
page.caption,
page.bitmap,
page.active,
close_button_state,
x_extent);
wxCoord tab_height = m_tabCtrlHeight;
//if( !page.active )
// tab_height -= 2;
wxCoord tab_width = tab_size.x - 1;
wxCoord tab_x = in_rect.x;
wxCoord tab_y = in_rect.y + in_rect.height - tab_height;
caption = page.caption;
// select pen, brush and font for the tab to be drawn
if( page.active )
{
dc.SetFont( m_selectedFont );
texty = selected_texty;
}
else
{
dc.SetFont( m_normalFont );
texty = normal_texty;
}
// create points that will make the tab outline
int clip_width = tab_width;
if (tab_x + clip_width > in_rect.x + in_rect.width)
clip_width = (in_rect.x + in_rect.width) - tab_x;
/*
wxPoint clip_points[6];
clip_points[0] = wxPoint(tab_x, tab_y+tab_height-3);
clip_points[1] = wxPoint(tab_x, tab_y+2);
clip_points[2] = wxPoint(tab_x+2, tab_y);
clip_points[3] = wxPoint(tab_x+clip_width-1, tab_y);
clip_points[4] = wxPoint(tab_x+clip_width+1, tab_y+2);
clip_points[5] = wxPoint(tab_x+clip_width+1, tab_y+tab_height-3);
// FIXME: these ports don't provide wxRegion ctor from array of points
#if !defined(__WXDFB__) && !defined(__WXCOCOA__)
// set the clipping region for the tab --
wxRegion clipping_region(WXSIZEOF(clip_points), clip_points);
dc.SetClippingRegion(clipping_region);
#endif // !wxDFB && !wxCocoa
*/
// since the above code above doesn't play well with WXDFB or WXCOCOA,
// we'll just use a rectangle for the clipping region for now --
dc.SetClippingRegion( tab_x, tab_y, clip_width + 1, tab_height - 3 );
wxPoint border_points[6];
if( m_flags & wxAUI_NB_BOTTOM )
{
border_points[ 0 ] = wxPoint( tab_x, tab_y );
border_points[ 1 ] = wxPoint( tab_x, tab_y + tab_height - 6 );
border_points[ 2 ] = wxPoint( tab_x + 2, tab_y + tab_height - 4 );
border_points[ 3 ] = wxPoint( tab_x + tab_width - 2, tab_y + tab_height - 4 );
border_points[ 4 ] = wxPoint( tab_x + tab_width, tab_y + tab_height - 6 );
border_points[ 5 ] = wxPoint( tab_x + tab_width, tab_y );
}
else //if (m_flags & wxAUI_NB_TOP) {}
{
border_points[ 0 ] = wxPoint( tab_x, tab_y + tab_height - 4 );
border_points[ 1 ] = wxPoint( tab_x, tab_y + 6 );
border_points[ 2 ] = wxPoint( tab_x + 6, tab_y );
border_points[ 3 ] = wxPoint( tab_x + tab_width - 2, tab_y );
border_points[ 4 ] = wxPoint( tab_x + tab_width, tab_y + 2 );
border_points[ 5 ] = wxPoint( tab_x + tab_width, tab_y + tab_height - 4 );
}
// TODO: else if (m_flags &wxAUI_NB_LEFT) {}
// TODO: else if (m_flags &wxAUI_NB_RIGHT) {}
int drawn_tab_yoff = border_points[ 1 ].y;
int drawn_tab_height = border_points[ 0 ].y - border_points[ 1 ].y;
// if( page.active )
// {
// dc.SetBrush( m_BgColor );
// dc.SetPen( * wxTRANSPARENT_PEN );
// dc.DrawRectangle( tab_x + 1, tab_height, tab_width - 1, tab_height + 2 );
// }
// draw tab outline
dc.SetPen( m_borderPen );
dc.SetBrush( * wxTRANSPARENT_BRUSH );
dc.DrawPolygon( WXSIZEOF( border_points ), border_points );
// there are two horizontal grey lines at the bottom of the tab control,
// this gets rid of the top one of those lines in the tab control
if( page.active )
{
if( m_flags & wxAUI_NB_BOTTOM )
dc.SetPen( wxPen( wxColour( wxAuiStepColour( m_baseColour, 170 ) ) ) );
// TODO: else if (m_flags &wxAUI_NB_LEFT) {}
// TODO: else if (m_flags &wxAUI_NB_RIGHT) {}
else //for wxAUI_NB_TOP
dc.SetPen( m_BgColor ); //dc.SetPen( m_base_colour_pen );
dc.DrawLine( border_points[ 0 ].x + 1,
border_points[ 0 ].y,
border_points[ 5 ].x,
border_points[ 5 ].y );
}
int text_offset = tab_x + 8;
int close_button_width = 0;
if( close_button_state != wxAUI_BUTTON_STATE_HIDDEN )
{
close_button_width = m_activeCloseBmp.GetWidth();
}
int bitmap_offset = 0;
if (page.bitmap.IsOk())
{
bitmap_offset = tab_x + 8;
// draw bitmap
dc.DrawBitmap(page.bitmap,
bitmap_offset,
drawn_tab_yoff + (drawn_tab_height/2) - (page.bitmap.GetHeight()/2),
true);
text_offset = bitmap_offset + page.bitmap.GetWidth();
text_offset += 3; // bitmap padding
}
else
{
text_offset = tab_x + 8;
}
wxString draw_text = wxAuiChopText(dc,
caption,
tab_width - (text_offset-tab_x) - close_button_width);
dc.SetTextForeground( page.active ? m_SelTextFgColour : m_TextFgColor );
// draw tab text
dc.DrawText(draw_text,
text_offset,
drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2) - 1);
// draw close button if necessary
if (close_button_state != wxAUI_BUTTON_STATE_HIDDEN)
{
wxBitmap bmp = m_disabledCloseBmp;
if (close_button_state == wxAUI_BUTTON_STATE_HOVER ||
close_button_state == wxAUI_BUTTON_STATE_PRESSED)
{
bmp = m_activeCloseBmp;
}
wxRect rect(tab_x + tab_width - close_button_width - 1,
tab_y + (tab_height/2) - (bmp.GetHeight()/2) - 2,
close_button_width,
tab_height);
IndentPressedBitmap(&rect, close_button_state);
dc.DrawBitmap(bmp, rect.x, rect.y, true);
*out_button_rect = rect;
}
*out_tab_rect = wxRect(tab_x, tab_y, tab_width, tab_height);
dc.DestroyClippingRegion();
}
// -------------------------------------------------------------------------------- //
// guAuiNotebook
// -------------------------------------------------------------------------------- //
guAuiNotebook::guAuiNotebook() : wxAuiNotebook()
{
SetArtProvider( new guAuiTabArt() );
}
// -------------------------------------------------------------------------------- //
guAuiNotebook::guAuiNotebook( wxWindow * parent, wxWindowID id, const wxPoint &pos,
const wxSize &size, long style ) :
wxAuiNotebook( parent, id, pos, size, style | wxBORDER_NONE | wxNO_BORDER )
{
SetArtProvider( new guAuiTabArt() );
wxAuiDockArt * AuiDockArt = m_mgr.GetArtProvider();
wxColour BaseColor = guCOLOR_BASE;
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, guCOLOR_CAPTION_TEXT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_GRADIENT_ACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, guCOLOR_CAPTION_INACTIVE );
AuiDockArt->SetColour( wxAUI_DOCKART_SASH_COLOUR, guCOLOR_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_CAPTION_SIZE, guSIZE_CAPTION );
AuiDockArt->SetMetric( wxAUI_DOCKART_PANE_BORDER_SIZE, guSIZE_BORDER );
AuiDockArt->SetMetric( wxAUI_DOCKART_SASH_SIZE, guSIZE_SASH );
AuiDockArt->SetMetric( wxAUI_DOCKART_GRADIENT_TYPE, guGRADIENT_TYPE );
}
// -------------------------------------------------------------------------------- //
guAuiNotebook::~guAuiNotebook()
{
}
// UpdateTabCtrlHeight() does the actual tab resizing. It's meant
// to be used interally
// -------------------------------------------------------------------------------- //
bool guAuiNotebook::UpdateTabCtrlHeight()
{
// get the tab ctrl height we will use
//int height = CalculateTabCtrlHeight();
wxAuiTabArt * ArtProvider = m_tabs.GetArtProvider();
m_tabCtrlHeight = guAUI_TAB_HEIGHT;
wxAuiPaneInfoArray &ALlPanes = m_mgr.GetAllPanes();
size_t PaneCount = ALlPanes.GetCount();
for( size_t PaneIndex = 0; PaneIndex < PaneCount; ++PaneIndex )
{
wxAuiPaneInfo &Pane = ALlPanes.Item( PaneIndex );
if( Pane.name == wxT( "dummy" ) )
continue;
wxTabFrame * TabFrame = ( wxTabFrame * ) Pane.window;
wxAuiTabCtrl * Tabs = TabFrame->m_tabs;
TabFrame->SetTabCtrlHeight( m_tabCtrlHeight );
Tabs->SetArtProvider( ArtProvider->Clone() );
TabFrame->DoSizing();
}
return true;
}
// -------------------------------------------------------------------------------- //
void guAuiNotebook::AddId( wxWindow * ptr, const wxString &id )
{
if( m_PagePtrs.Index( ptr ) == wxNOT_FOUND )
{
m_PageIds.Add( id );
m_PagePtrs.Add( ptr );
}
}
// -------------------------------------------------------------------------------- //
wxString guAuiNotebook::GetPageId( const wxWindow * ptr )
{
int Count = m_PagePtrs.Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_PagePtrs[ Index ] == ptr )
{
return m_PageIds[ Index ];
}
}
return wxEmptyString;
}
// -------------------------------------------------------------------------------- //
wxString guAuiNotebook::SavePerspective( void )
{
// Build list of panes/tabs
wxString tabs;
wxAuiPaneInfoArray &all_panes = m_mgr.GetAllPanes();
const size_t pane_count = all_panes.GetCount();
for( size_t i = 0; i < pane_count; ++i )
{
wxAuiPaneInfo &pane = all_panes.Item( i );
if( pane.name == wxT( "dummy" ) )
continue;
wxTabFrame * tabframe = ( wxTabFrame * ) pane.window;
if( !tabs.empty() )
tabs += wxT( "|" );
tabs += pane.name;
tabs += wxT( "=" );
// add tab id's
size_t page_count = tabframe->m_tabs->GetPageCount();
for( size_t p = 0; p < page_count; ++p )
{
wxAuiNotebookPage &page = tabframe->m_tabs->GetPage( p );
const size_t page_idx = m_tabs.GetIdxFromWindow( page.window );
if( p )
tabs += wxT( "," );
if( ( int ) page_idx == m_curPage )
tabs += wxT( "*" );
else if( ( int ) p == tabframe->m_tabs->GetActivePage() )
tabs += wxT( "+" );
//tabs += wxString::Format( wxT( "%02lu[%s]" ), page_idx, page.caption.c_str() );
tabs += wxString::Format( wxT( "%02lu[%s]" ), page_idx, GetPageId( page.window ).c_str() );
}
}
tabs += wxT( "@" );
// Add frame perspective
tabs += m_mgr.SavePerspective();
return tabs;
}
// -------------------------------------------------------------------------------- //
bool guAuiNotebook::LoadPerspective( const wxString &layout )
{
// Remove all tab ctrls (but still keep them in main index)
const size_t tab_count = m_tabs.GetPageCount();
for( size_t i = 0; i < tab_count; ++i )
{
wxWindow * wnd = m_tabs.GetWindowFromIdx( i );
// find out which onscreen tab ctrl owns this tab
wxAuiTabCtrl * ctrl;
int ctrl_idx;
if( !FindTab( wnd, &ctrl, &ctrl_idx ) )
return false;
// remove the tab from ctrl
if( !ctrl->RemovePage( wnd ) )
return false;
}
RemoveEmptyTabFrames();
size_t sel_page = 0;
wxString tabs = layout.BeforeFirst( wxT( '@' ) );
while( 1 )
{
const wxString tab_part = tabs.BeforeFirst( wxT( '|' ) );
// if the string is empty, we're done parsing
if( tab_part.empty() )
break;
// Get pane name
const wxString pane_name = tab_part.BeforeFirst( wxT( '=' ) );
// create a new tab frame
wxTabFrame * new_tabs = new wxTabFrame;
new_tabs->m_tabs = new wxAuiTabCtrl( this,
m_tabIdCounter++,
wxDefaultPosition,
wxDefaultSize,
wxNO_BORDER | wxWANTS_CHARS );
new_tabs->m_tabs->SetArtProvider( m_tabs.GetArtProvider()->Clone() );
new_tabs->SetTabCtrlHeight( m_tabCtrlHeight );
new_tabs->m_tabs->SetFlags( m_flags );
wxAuiTabCtrl * dest_tabs = new_tabs->m_tabs;
// create a pane info structure with the information
// about where the pane should be added
wxAuiPaneInfo pane_info = wxAuiPaneInfo().Name( pane_name ).Bottom().CaptionVisible( false );
m_mgr.AddPane( new_tabs, pane_info );
// Get list of tab id's and move them to pane
wxString tab_list = tab_part.AfterFirst( wxT( '=' ) );
while( 1 )
{
wxString tab = tab_list.BeforeFirst( wxT( ',' ) );
if( tab.empty() )
break;
tab_list = tab_list.AfterFirst( wxT( ',' ) );
// Check if this page has an 'active' marker
const wxChar c = tab[ 0 ];
if( c == wxT( '+' ) || c == wxT( '*' ) )
{
tab = tab.Mid( 1, 2 );
}
const size_t tab_idx = wxAtoi( tab.c_str() );
if( tab_idx >= GetPageCount() )
continue;
// Move tab to pane
wxAuiNotebookPage &page = m_tabs.GetPage( tab_idx );
const size_t newpage_idx = dest_tabs->GetPageCount();
dest_tabs->InsertPage( page.window, page, newpage_idx );
if( c == wxT( '+' ) )
dest_tabs->SetActivePage( newpage_idx );
else if( c == wxT( '*' ) )
sel_page = tab_idx;
}
dest_tabs->DoShowHide();
tabs = tabs.AfterFirst( wxT( '|' ) );
}
// Load the frame perspective
const wxString frames = layout.AfterFirst( wxT( '@' ) );
m_mgr.LoadPerspective( frames );
// Force refresh of selection
m_curPage = -1;
SetSelection( sel_page );
return true;
}
// -------------------------------------------------------------------------------- //
wxAuiPaneInfo & guAuiNotebook::GetPane( wxWindow * window )
{
return m_mgr.GetPane( window );
}
// -------------------------------------------------------------------------------- //
wxAuiPaneInfo & guAuiNotebook::GetPane( const wxString &name )
{
return m_mgr.GetPane( name );
}
// -------------------------------------------------------------------------------- //
wxAuiPaneInfoArray & guAuiNotebook::GetAllPanes( void )
{
return m_mgr.GetAllPanes();
}
}
// -------------------------------------------------------------------------------- //
| 21,069
|
C++
|
.cpp
| 506
| 34.780632
| 110
| 0.530142
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,631
|
AutoScrollText.cpp
|
anonbeat_guayadeque/src/ui/autoscrolltext/AutoScrollText.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AutoScrollText.h"
#include "Utils.h"
#include <wx/dcclient.h>
#include <wx/region.h>
#define guSCROLL_START_TIMEOUT 300
#define guSCROLL_TIMEOUT 300
#define guSCROLL_STEP_WIDTH 16
#define guSCROLL_TIMER_START 11
#define guSCROLL_TIMER_SCROLL 12
namespace Guayadeque {
BEGIN_EVENT_TABLE( guAutoScrollText, wxControl )
EVT_MOUSE_EVENTS( guAutoScrollText::OnMouseEvents )
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guAutoScrollText::guAutoScrollText( wxWindow * parent, const wxString &label, const wxSize &size ) :
wxControl( parent, wxID_ANY, wxDefaultPosition, size, wxBORDER_NONE ),
m_StartTimer( this, guSCROLL_TIMER_START ),
m_ScrollTimer( this, guSCROLL_TIMER_SCROLL )
{
m_ScrollPos = 0;
m_ScrollQuantum = 1;
m_VisWidth = 0;
m_AllowScroll = false;
m_DefaultSize = size;
SetLabel( label );
Bind( wxEVT_PAINT, &guAutoScrollText::OnPaint, this );
Bind( wxEVT_TIMER, &guAutoScrollText::OnStartTimer, this, guSCROLL_TIMER_START );
Bind( wxEVT_TIMER, &guAutoScrollText::OnScrollTimer, this, guSCROLL_TIMER_SCROLL );
Bind( wxEVT_SIZE, &guAutoScrollText::OnSize, this );
}
// -------------------------------------------------------------------------------- //
guAutoScrollText::~guAutoScrollText()
{
Unbind( wxEVT_PAINT, &guAutoScrollText::OnPaint, this );
Unbind( wxEVT_TIMER, &guAutoScrollText::OnStartTimer, this, guSCROLL_TIMER_START );
Unbind( wxEVT_TIMER, &guAutoScrollText::OnScrollTimer, this, guSCROLL_TIMER_SCROLL );
Unbind( wxEVT_SIZE, &guAutoScrollText::OnSize, this );
}
// -------------------------------------------------------------------------------- //
wxSize guAutoScrollText::DoGetBestSize() const
{
wxSize RetVal;
RetVal.x = ( m_DefaultSize.x != wxNOT_FOUND ) ? wxMin( m_DefaultSize.x, m_LabelExtent.x ) : m_LabelExtent.x;
RetVal.y = ( m_DefaultSize.y != wxNOT_FOUND ) ? wxMin( m_DefaultSize.y, m_LabelExtent.y ) : m_LabelExtent.y;
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::SetLabel( const wxString &label )
{
m_Label = label;
GetTextExtent( label, &m_LabelExtent.x, &m_LabelExtent.y );
m_ScrollPos = 0;
m_ScrollQuantum = 1;
//guLogMessage( wxT( "LabelExtent: %u Width: %u %i" ), m_LabelExtent.x, m_VisWidth, m_ScrollTimer.IsRunning() );
if( m_ScrollTimer.IsRunning() && !( m_LabelExtent.x > m_VisWidth ) )
{
m_ScrollTimer.Stop();
}
Refresh();
Update();
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::OnPaint( wxPaintEvent &event )
{
wxPaintDC dc( this );
PrepareDC( dc );
dc.SetBackgroundMode( wxTRANSPARENT );
dc.SetTextForeground( GetForegroundColour() );
dc.SetFont( GetFont() );
dc.DrawText( m_Label.Mid( m_ScrollPos ), 0, 0 );
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::OnSize( wxSizeEvent &event )
{
wxRect Size = event.GetSize();
//guLogMessage( wxT( "Size Event: %i, %i" ), Size.GetWidth(), Size.GetHeight() );
m_VisWidth = Size.GetWidth();
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::OnMouseEvents( wxMouseEvent &event )
{
if( event.Moving() && ( m_LabelExtent.x > m_VisWidth ) )
{
if( !m_ScrollTimer.IsRunning() )
{
// No need to stop the timer first anymore
//if( m_StartTimer.IsRunning() )
// m_StartTimer.Stop();
m_StartTimer.Start( guSCROLL_START_TIMEOUT, wxTIMER_ONE_SHOT );
}
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
bool inline MouseIsOver( const wxRect &rect )
{
int MouseX, MouseY;
wxGetMousePosition( &MouseX, &MouseY );
return rect.Contains( MouseX, MouseY );
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::OnStartTimer( wxTimerEvent &event )
{
if( MouseIsOver( GetScreenRect() ) )
{
m_ScrollTimer.Start( guSCROLL_TIMEOUT, wxTIMER_CONTINUOUS );
}
}
// -------------------------------------------------------------------------------- //
void guAutoScrollText::OnScrollTimer( wxTimerEvent &event )
{
if( !MouseIsOver( GetScreenRect() ) )
{
if( m_ScrollQuantum > 0 )
m_ScrollQuantum = -1;
if( !m_ScrollPos )
{
m_ScrollTimer.Stop();
return;
}
}
else if( m_ScrollQuantum > 0 )
{
int ActualWidth;
int ActualHeight;
GetTextExtent( m_Label.Mid( m_ScrollPos ), &ActualWidth, &ActualHeight );
if( ( ActualWidth + guSCROLL_STEP_WIDTH ) < m_VisWidth )
{
m_ScrollQuantum = -1;
}
}
else
{
if( !m_ScrollPos )
{
m_ScrollQuantum = 1;
}
}
m_ScrollPos += m_ScrollQuantum;
//guLogMessage( wxT( "Actual ScrollPos: %i ScrollQ: %i" ), m_ScrollPos, m_ScrollQuantum );
Refresh();
}
}
// -------------------------------------------------------------------------------- //
| 6,383
|
C++
|
.cpp
| 166
| 34.26506
| 117
| 0.547611
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,632
|
Equalizer.cpp
|
anonbeat_guayadeque/src/ui/equalizer/Equalizer.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "Equalizer.h"
#include "Config.h"
#include "Images.h"
#include "Utils.h"
#include <wx/arrimpl.cpp>
#include <wx/tokenzr.h>
#include <wx/fileconf.h>
namespace Guayadeque {
WX_DEFINE_OBJARRAY( guEQPresetArray )
// -------------------------------------------------------------------------------- //
bool ReadEQPresets( const wxString &value, wxArrayInt &preset )
{
long CurVal;
int count;
wxArrayString Values = wxStringTokenize( value, wxT( "," ), wxTOKEN_RET_EMPTY_ALL );
if( ( count = Values.Count() ) == guEQUALIZER_BAND_COUNT )
{
for( int index = 0; index < count; index++ )
{
if( Values[ index ].ToLong( &CurVal ) )
{
preset.Add( CurVal );
}
else
break;
}
return ( preset.Count() == guEQUALIZER_BAND_COUNT );
}
return false;
}
// -------------------------------------------------------------------------------- //
guEq10Band::guEq10Band( wxWindow * parent, guMediaCtrl * mediactrl ) //wxDialog( parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 400,250 ), wxDEFAULT_DIALOG_STYLE )
{
m_MediaCtrl = mediactrl;
m_BandChanged = false;
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPoint WindowPos;
WindowPos.x = Config->ReadNum( CONFIG_KEY_EQUALIZER_POS_X, -1, CONFIG_PATH_EQUALIZER );
WindowPos.y = Config->ReadNum( CONFIG_KEY_EQUALIZER_POS_Y, -1, CONFIG_PATH_EQUALIZER );
wxSize WindowSize;
WindowSize.x = Config->ReadNum( CONFIG_KEY_EQUALIZER_WIDTH, 400, CONFIG_PATH_EQUALIZER );
WindowSize.y = Config->ReadNum( CONFIG_KEY_EQUALIZER_HEIGHT, 250, CONFIG_PATH_EQUALIZER );
Create( parent, wxID_ANY, _( "Equalizer" ), WindowPos, WindowSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX );
wxFileConfig * EqConfig = new wxFileConfig( wxEmptyString, wxEmptyString, guPATH_EQUALIZERS_FILENAME );
if( EqConfig )
{
EqConfig->SetPath( wxT( "Equalizers" ) );
wxString EntryName;
wxString EntryValue;
wxArrayInt Presets;
long index;
if( EqConfig->GetFirstEntry( EntryName, index ) )
{
do {
EqConfig->Read( EntryName, &EntryValue, wxEmptyString );
if( !EntryValue.IsEmpty() )
{
//guLogMessage( wxT( "Entry%02u ) %s=%s" ), index, EntryName.c_str(), EntryValue.c_str() );
Presets.Empty();
if( ReadEQPresets( EntryValue, Presets ) && Presets.Count() == guEQUALIZER_BAND_COUNT )
{
m_EQPresets.Add( new guEQPreset( EntryName, Presets ) );
}
}
} while( EqConfig->GetNextEntry( EntryName, index ) );
}
delete EqConfig;
}
//
SetSizeHints( wxSize( 450,260 ), wxDefaultSize );
wxBoxSizer* MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* TopSizer;
TopSizer = new wxBoxSizer( wxHORIZONTAL );
TopSizer->Add( 0, 0, 1, wxEXPAND, 5 );
wxStaticText * PresetLabel;
PresetLabel = new wxStaticText( this, wxID_ANY, _( "Preset:" ), wxDefaultPosition, wxDefaultSize, 0 );
PresetLabel->Wrap( -1 );
TopSizer->Add( PresetLabel, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_PresetComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,-1 ), 0, NULL, 0 );
wxString LastPreset = Config->ReadStr( CONFIG_KEY_EQUALIZER_LAST_PRESET, wxEmptyString, CONFIG_PATH_EQUALIZER );
int LastPresetIndex = wxNOT_FOUND;
int count = m_EQPresets.Count();
for( int index = 0; index < count; index++ )
{
m_PresetComboBox->Append( m_EQPresets[ index ].m_Name );
if( m_EQPresets[ index ].m_Name == LastPreset )
LastPresetIndex = index;
}
TopSizer->Add( m_PresetComboBox, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT, 5 );
m_SaveButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_doc_save ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_SaveButton->Enable( false );
TopSizer->Add( m_SaveButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT, 5 );
m_DelButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_edit_clear ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DelButton->Enable( false );
TopSizer->Add( m_DelButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT, 5 );
m_ResetButton = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_tiny_reload ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
TopSizer->Add( m_ResetButton, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxRIGHT, 5 );
MainSizer->Add( TopSizer, 0, wxEXPAND, 5 );
wxBoxSizer* BandsSizer;
BandsSizer = new wxBoxSizer( wxHORIZONTAL );
wxBoxSizer * LabelsSizer;
LabelsSizer = new wxBoxSizer( wxVERTICAL );
wxStaticText * Label = new wxStaticText( this, wxID_ANY, wxT("dBs"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxTOP|wxALIGN_RIGHT, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("12"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("6"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("3"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("-3"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("-6"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
LabelsSizer->Add( 0, 0, 1, wxEXPAND, 5 );
Label = new wxStaticText( this, wxID_ANY, wxT("-12"), wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxALIGN_RIGHT, 5 );
Label = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
Label->Wrap( -1 );
LabelsSizer->Add( Label, 0, wxRIGHT|wxLEFT|wxALIGN_RIGHT, 5 );
BandsSizer->Add( LabelsSizer, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer00;
BandSizer00 = new wxBoxSizer( wxVERTICAL );
m_Values[ 0 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 0 ]->Wrap( -1 );
BandSizer00->Add( m_Values[ 0 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 0 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 0 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 0 ]->SetLabel( wxT( "0" ) );
BandSizer00->Add( m_Bands[ 0 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label0 = new wxStaticText( this, wxID_ANY, wxT("30"), wxDefaultPosition, wxDefaultSize, 0 );
Label0->Wrap( -1 );
BandSizer00->Add( Label0, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer00, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer01;
BandSizer01 = new wxBoxSizer( wxVERTICAL );
m_Values[ 1 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 1 ]->Wrap( -1 );
BandSizer01->Add( m_Values[ 1 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 1 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 1 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 1 ]->SetLabel( wxT( "1" ) );
BandSizer01->Add( m_Bands[ 1 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label1 = new wxStaticText( this, wxID_ANY, wxT("60"), wxDefaultPosition, wxDefaultSize, 0 );
Label1->Wrap( -1 );
BandSizer01->Add( Label1, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer01, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer02;
BandSizer02 = new wxBoxSizer( wxVERTICAL );
m_Values[ 2 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 2 ]->Wrap( -1 );
BandSizer02->Add( m_Values[ 2 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 2 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 2 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 2 ]->SetLabel( wxT( "2" ) );
BandSizer02->Add( m_Bands[ 2 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label2 = new wxStaticText( this, wxID_ANY, wxT("120"), wxDefaultPosition, wxDefaultSize, 0 );
Label2->Wrap( -1 );
BandSizer02->Add( Label2, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer02, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer03;
BandSizer03 = new wxBoxSizer( wxVERTICAL );
m_Values[ 3 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 3 ]->Wrap( -1 );
BandSizer03->Add( m_Values[ 3 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 3 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 3 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 3 ]->SetLabel( wxT( "3" ) );
BandSizer03->Add( m_Bands[ 3 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label3 = new wxStaticText( this, wxID_ANY, wxT("250"), wxDefaultPosition, wxDefaultSize, 0 );
Label3->Wrap( -1 );
BandSizer03->Add( Label3, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer03, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer04;
BandSizer04 = new wxBoxSizer( wxVERTICAL );
m_Values[ 4 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 4 ]->Wrap( -1 );
BandSizer04->Add( m_Values[ 4 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 4 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 4 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 4 ]->SetLabel( wxT( "4" ) );
BandSizer04->Add( m_Bands[ 4 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label4 = new wxStaticText( this, wxID_ANY, wxT("500"), wxDefaultPosition, wxDefaultSize, 0 );
Label4->Wrap( -1 );
BandSizer04->Add( Label4, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer04, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer05;
BandSizer05 = new wxBoxSizer( wxVERTICAL );
m_Values[ 5 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 5 ]->Wrap( -1 );
BandSizer05->Add( m_Values[ 5 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 5 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 5 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 5 ]->SetLabel( wxT( "5" ) );
BandSizer05->Add( m_Bands[ 5 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label5 = new wxStaticText( this, wxID_ANY, wxT("1K"), wxDefaultPosition, wxDefaultSize, 0 );
Label5->Wrap( -1 );
BandSizer05->Add( Label5, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer05, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer06;
BandSizer06 = new wxBoxSizer( wxVERTICAL );
m_Values[ 6 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 6 ]->Wrap( -1 );
BandSizer06->Add( m_Values[ 6 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 6 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 6 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 6 ]->SetLabel( wxT( "6" ) );
BandSizer06->Add( m_Bands[ 6 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label6 = new wxStaticText( this, wxID_ANY, wxT("2K"), wxDefaultPosition, wxDefaultSize, 0 );
Label6->Wrap( -1 );
BandSizer06->Add( Label6, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer06, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer07;
BandSizer07 = new wxBoxSizer( wxVERTICAL );
m_Values[ 7 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 7 ]->Wrap( -1 );
BandSizer07->Add( m_Values[ 7 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 7 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 7 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 7 ]->SetLabel( wxT( "7" ) );
BandSizer07->Add( m_Bands[ 7 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label7 = new wxStaticText( this, wxID_ANY, wxT("4K"), wxDefaultPosition, wxDefaultSize, 0 );
Label7->Wrap( -1 );
BandSizer07->Add( Label7, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer07, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer08;
BandSizer08 = new wxBoxSizer( wxVERTICAL );
m_Values[ 8 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 8 ]->Wrap( -1 );
BandSizer08->Add( m_Values[ 8 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 8 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 8 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 8 ]->SetLabel( wxT( "8" ) );
BandSizer08->Add( m_Bands[ 8 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label8 = new wxStaticText( this, wxID_ANY, wxT("8K"), wxDefaultPosition, wxDefaultSize, 0 );
Label8->Wrap( -1 );
BandSizer08->Add( Label8, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer08, 1, wxEXPAND, 5 );
wxBoxSizer* BandSizer09;
BandSizer09 = new wxBoxSizer( wxVERTICAL );
m_Values[ 9 ] = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
m_Values[ 9 ]->Wrap( -1 );
BandSizer09->Add( m_Values[ 9 ], 0, wxALIGN_CENTER_HORIZONTAL|wxTOP|wxRIGHT|wxLEFT, 5 );
m_Bands[ 9 ] = new wxSlider( this, wxID_ANY, m_MediaCtrl->GetEqualizerBand( 9 ), -120, 120, wxDefaultPosition, wxDefaultSize, wxSL_INVERSE|wxSL_VERTICAL );
m_Bands[ 9 ]->SetLabel( wxT( "9" ) );
BandSizer09->Add( m_Bands[ 9 ], 1, wxEXPAND|wxRIGHT|wxLEFT, 5 );
wxStaticText * Label9 = new wxStaticText( this, wxID_ANY, wxT("16K"), wxDefaultPosition, wxDefaultSize, 0 );
Label9->Wrap( -1 );
BandSizer09->Add( Label9, 0, wxALIGN_CENTER_HORIZONTAL, 5 );
BandsSizer->Add( BandSizer09, 1, wxEXPAND, 5 );
MainSizer->Add( BandsSizer, 1, wxEXPAND|wxBOTTOM, 5 );
wxStdDialogButtonSizer * EQBtnSizer;
EQBtnSizer = new wxStdDialogButtonSizer();
wxButton * EQBtnOK;
EQBtnOK = new wxButton( this, wxID_OK );
EQBtnSizer->AddButton( EQBtnOK );
EQBtnSizer->SetAffirmativeButton( EQBtnOK );
EQBtnSizer->Realize();
MainSizer->Add( EQBtnSizer, 0, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
for( int Index = 0; Index < guEQUALIZER_BAND_COUNT; Index++ )
{
m_Values[ Index ]->SetLabel( wxString::Format( wxT( "%.1f" ), double( m_Bands[ Index ]->GetValue() ) / 10.0 ) );
m_Bands[ Index ]->Bind( wxEVT_SCROLL_CHANGED, &guEq10Band::OnBandChanged, this );
m_Bands[ Index ]->Bind( wxEVT_SCROLL_THUMBTRACK, &guEq10Band::OnUpdateLabel, this );
}
this->SetSizer( MainSizer );
this->Layout();
EQBtnOK->SetDefault();
// Bind Events
m_PresetComboBox->Bind( wxEVT_COMBOBOX, &guEq10Band::OnPresetSelected, this );
m_PresetComboBox->Bind( wxEVT_TEXT, &guEq10Band::OnPresetText, this );
m_ResetButton->Bind( wxEVT_BUTTON, &guEq10Band::OnResetPreset, this );
m_SaveButton->Bind( wxEVT_BUTTON, &guEq10Band::OnAddPreset, this );
m_DelButton->Bind( wxEVT_BUTTON, &guEq10Band::OnDelPreset, this );
if( LastPresetIndex != wxNOT_FOUND )
{
m_PresetComboBox->SetSelection( LastPresetIndex );
}
m_PresetComboBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guEq10Band::~guEq10Band()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
wxPoint WindowPos = GetPosition();
Config->WriteNum( CONFIG_KEY_EQUALIZER_POS_X, WindowPos.x, CONFIG_PATH_EQUALIZER );
Config->WriteNum( CONFIG_KEY_EQUALIZER_POS_Y, WindowPos.y, CONFIG_PATH_EQUALIZER );
wxSize WindowSize = GetSize();
Config->WriteNum( CONFIG_KEY_EQUALIZER_WIDTH, WindowSize.x, CONFIG_PATH_EQUALIZER );
Config->WriteNum( CONFIG_KEY_EQUALIZER_HEIGHT, WindowSize.y, CONFIG_PATH_EQUALIZER );
Config->WriteStr( CONFIG_KEY_EQUALIZER_LAST_PRESET, m_BandChanged ? wxT( "" ) : m_PresetComboBox->GetValue(), CONFIG_PATH_EQUALIZER );
wxFileConfig * EqConfig = new wxFileConfig( wxEmptyString, wxEmptyString, wxGetHomeDir() + wxT( "/.guayadeque/equalizers.conf" ) );
if( EqConfig )
{
EqConfig->DeleteGroup( wxT( "Equalizers" ) );
EqConfig->SetPath( wxT( "Equalizers" ) );
int count = m_EQPresets.Count();
for( int index = 0; index < count; index++ )
{
if( !EqConfig->Write( m_EQPresets[ index ].m_Name, wxString::Format( wxT( "%i,%i,%i,%i,%i,%i,%i,%i,%i,%i" ),
m_EQPresets[ index ].m_Sets[ 0 ],
m_EQPresets[ index ].m_Sets[ 1 ],
m_EQPresets[ index ].m_Sets[ 2 ],
m_EQPresets[ index ].m_Sets[ 3 ],
m_EQPresets[ index ].m_Sets[ 4 ],
m_EQPresets[ index ].m_Sets[ 5 ],
m_EQPresets[ index ].m_Sets[ 6 ],
m_EQPresets[ index ].m_Sets[ 7 ],
m_EQPresets[ index ].m_Sets[ 8 ],
m_EQPresets[ index ].m_Sets[ 9 ] ) ) )
guLogError( wxT( "Error writing key %s" ), m_EQPresets[ index ].m_Name.c_str() );
}
delete EqConfig;
}
// Unbind Events
m_PresetComboBox->Unbind( wxEVT_COMBOBOX, &guEq10Band::OnPresetSelected, this );
m_PresetComboBox->Unbind( wxEVT_TEXT, &guEq10Band::OnPresetText, this );
m_ResetButton->Unbind( wxEVT_BUTTON, &guEq10Band::OnResetPreset, this );
m_SaveButton->Unbind( wxEVT_BUTTON, &guEq10Band::OnAddPreset, this );
m_DelButton->Unbind( wxEVT_BUTTON, &guEq10Band::OnDelPreset, this );
for( int Index = 0; Index < guEQUALIZER_BAND_COUNT; Index++ )
{
m_Bands[ Index ]->Unbind( wxEVT_SCROLL_CHANGED, &guEq10Band::OnBandChanged, this );
m_Bands[ Index ]->Unbind( wxEVT_SCROLL_THUMBTRACK, &guEq10Band::OnUpdateLabel, this );
}
}
// -------------------------------------------------------------------------------- //
bool FindPresetName( const wxString &name, guEQPresetArray &presets )
{
int count = presets.Count();
for( int index = 0; index < count; index++ )
{
if( presets[ index ].m_Name == name )
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnUpdateLabel( wxScrollEvent &event )
{
wxSlider * Band = ( wxSlider * ) event.GetEventObject();
if( Band )
{
long BandIndex;
Band->GetLabel().ToLong( &BandIndex );
m_Values[ BandIndex ]->SetLabel( wxString::Format( wxT( "%.1f" ), double( event.GetPosition() ) / 10.0 ) );
m_Values[ BandIndex ]->GetContainingSizer()->Layout();
}
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnBandChanged( wxScrollEvent &event )
{
wxSlider * Band = ( wxSlider * ) event.GetEventObject();
if( Band )
{
long BandIndex;
Band->GetLabel().ToLong( &BandIndex );
//guLogMessage( wxT( "Band%u = %i (%i)" ), BandIndex, event.GetPosition(), m_PresetComboBox->GetSelection() );
m_MediaCtrl->SetEqualizerBand( BandIndex, event.GetPosition() );
if( m_PresetComboBox->GetSelection() != wxNOT_FOUND )
m_BandChanged = true;
OnPresetText( event );
m_Values[ BandIndex ]->SetLabel( wxString::Format( wxT( "%.1f" ), double( event.GetPosition() ) / 10.0 ) );
m_Values[ BandIndex ]->GetContainingSizer()->Layout();
}
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnPresetSelected( wxCommandEvent& event )
{
int Preset = event.GetInt();
if( Preset >= 0 )
{
for( int Index = 0; Index < guEQUALIZER_BAND_COUNT; Index++ )
{
m_Bands[ Index ]->SetValue( m_EQPresets[ Preset ].m_Sets[ Index ] );
m_Values[ Index ]->SetLabel( wxString::Format( wxT( "%.1f" ), double( m_EQPresets[ Preset ].m_Sets[ Index ] ) / 10.0 ) );
m_Values[ Index ]->GetContainingSizer()->Layout();
}
m_MediaCtrl->SetEqualizer( m_EQPresets[ Preset ].m_Sets );
m_DelButton->Enable( true );
m_SaveButton->Enable( false );
m_BandChanged = false;
}
else
{
m_DelButton->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnPresetText( wxCommandEvent& event )
{
int Sel = m_PresetComboBox->GetSelection();
m_SaveButton->Enable( m_PresetComboBox->GetCount() != 0 &&
( m_BandChanged || !FindPresetName( m_PresetComboBox->GetValue(), m_EQPresets ) ) );
m_DelButton->Enable( Sel != wxNOT_FOUND );
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnAddPreset( wxCommandEvent& event )
{
wxArrayInt EQSet;
for( int Index = 0; Index < guEQUALIZER_BAND_COUNT; Index++ )
{
EQSet.Add( m_Bands[ Index ]->GetValue() );
}
if( m_BandChanged && ( m_PresetComboBox->GetSelection() != wxNOT_FOUND ) )
{
m_EQPresets[ m_PresetComboBox->GetSelection() ].m_Sets = EQSet;
}
else
{
m_EQPresets.Add( new guEQPreset( m_PresetComboBox->GetValue(), EQSet ) );
m_PresetComboBox->Append( m_PresetComboBox->GetValue() );
m_PresetComboBox->SetSelection( m_EQPresets.Count() - 1 );
}
m_BandChanged = false;
OnPresetText( event );
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnDelPreset( wxCommandEvent& event )
{
int Sel = m_PresetComboBox->GetSelection();
if( Sel >= 0 )
{
m_PresetComboBox->Delete( Sel );
m_PresetComboBox->SetSelection( wxNOT_FOUND );
m_PresetComboBox->SetValue( wxEmptyString );
m_EQPresets.RemoveAt( Sel );
m_DelButton->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guEq10Band::OnResetPreset( wxCommandEvent &event )
{
for( int Index = 0; Index < guEQUALIZER_BAND_COUNT; Index++ )
{
m_Bands[ Index ]->SetValue( Index );
}
m_MediaCtrl->ResetEqualizer();
m_PresetComboBox->SetSelection( wxNOT_FOUND );
m_PresetComboBox->SetValue( wxEmptyString );
m_SaveButton->Enable( false );
m_DelButton->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
| 24,876
|
C++
|
.cpp
| 473
| 46.600423
| 176
| 0.624609
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,633
|
StaticBitmap.cpp
|
anonbeat_guayadeque/src/ui/staticbitmap/StaticBitmap.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "StaticBitmap.h"
#include "Utils.h"
namespace Guayadeque {
const wxEventType guStaticBitmapMouseOverEvent = wxNewEventType();
#define guSTATICBITMAP_MOUSE_OVER_TIMEOUT 500
// -------------------------------------------------------------------------------- //
guStaticBitmap::guStaticBitmap( wxWindow * parent, wxWindowID id, const wxBitmap &label, const wxPoint &pos, const wxSize &size, long style ) :
wxStaticBitmap( parent, id, label, pos, size, style )
{
m_MouseOverTimer = new guStaticBitmapTimer( this );
Bind( wxEVT_MOTION, &guStaticBitmap::OnMouse, this );
}
// -------------------------------------------------------------------------------- //
guStaticBitmap::~guStaticBitmap()
{
Unbind( wxEVT_MOTION, &guStaticBitmap::OnMouse, this );
if( m_MouseOverTimer )
{
delete m_MouseOverTimer;
}
}
// -------------------------------------------------------------------------------- //
void guStaticBitmap::OnMouse( wxMouseEvent &event )
{
if( m_MouseOverTimer->IsRunning() )
m_MouseOverTimer->Stop();
m_MouseOverTimer->Start( guSTATICBITMAP_MOUSE_OVER_TIMEOUT, wxTIMER_ONE_SHOT );
event.Skip();
}
// -------------------------------------------------------------------------------- //
// guStaticBitmapTimer
// -------------------------------------------------------------------------------- //
void guStaticBitmapTimer::Notify()
{
int MouseX, MouseY;
wxGetMousePosition( &MouseX, &MouseY );
wxRect WinRect = m_Bitmap->GetScreenRect();
if( WinRect.Contains( MouseX, MouseY ) )
{
wxCommandEvent event( guStaticBitmapMouseOverEvent, guEVT_STATICBITMAP_MOUSE_OVER );
event.SetEventObject( this );
m_Bitmap->GetEventHandler()->AddPendingEvent( event );
}
}
}
// -------------------------------------------------------------------------------- //
| 2,918
|
C++
|
.cpp
| 67
| 40.776119
| 143
| 0.54866
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,634
|
ItemListBox.cpp
|
anonbeat_guayadeque/src/ui/itemlistbox/ItemListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ItemListBox.h"
#include "Utils.h"
#include <wx/dnd.h>
namespace Guayadeque {
// -------------------------------------------------------------------------------- //
guListBox::guListBox( wxWindow * parent, guDbLibrary * db, const wxString &label, int flags ) :
guListView( parent, flags )
{
m_Db = db;
m_Items = new guListItems();
guListViewColumn * Column = new guListViewColumn( label, 0 );
InsertColumn( Column );
}
// -------------------------------------------------------------------------------- //
guListBox::~guListBox()
{
if( m_Items )
delete m_Items;
}
// -------------------------------------------------------------------------------- //
void guListBox::ReloadItems( bool reset )
{
wxArrayInt Selection;
int FirstVisible = 0; // = GetVisibleRowsBegin();
if( reset )
{
SetSelection( -1 );
}
else
{
FirstVisible = GetVisibleRowsBegin();
Selection = GetSelectedItems( false );
}
m_Items->Empty();
GetItemsList();
m_Items->Insert( new guListItem( 0, wxString::Format( wxT( "%s (%lu)" ), _( "All" ), m_Items->Count() ) ), 0 );
SetItemCount( m_Items->Count() );
if( !reset )
{
SetSelectedItems( Selection );
ScrollToRow( FirstVisible );
}
RefreshAll();
}
// -------------------------------------------------------------------------------- //
int guListBox::FindItemId( const int id )
{
int Count = m_Items->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( m_Items->Item( Index ).m_Id == id )
{
return Index;
}
}
return wxNOT_FOUND;
}
}
// -------------------------------------------------------------------------------- //
| 2,806
|
C++
|
.cpp
| 80
| 31.4375
| 115
| 0.505162
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,635
|
AccelListBox.cpp
|
anonbeat_guayadeque/src/ui/itemlistbox/AccelListBox.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "AccelListBox.h"
#include "Accelerators.h"
#include "Config.h"
#include "LibPanel.h"
#include "Preferences.h"
using namespace Guayadeque;
// -------------------------------------------------------------------------------- //
guAccelListBox::guAccelListBox( wxWindow * parent, guDbLibrary * db, const wxString &label ) :
guListBox( parent, db, label, wxLB_MULTIPLE | guLISTVIEW_ALLOWDRAG | guLISTVIEW_HIDE_HEADER )
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->RegisterObject( this );
Bind( guConfigUpdatedEvent, &guAccelListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
CreateAcceleratorTable();
}
// -------------------------------------------------------------------------------- //
guAccelListBox::~guAccelListBox()
{
guConfig * Config = ( guConfig * ) guConfig::Get();
Config->UnRegisterObject( this );
Unbind( guConfigUpdatedEvent, &guAccelListBox::OnConfigUpdated, this, ID_CONFIG_UPDATED );
}
// -------------------------------------------------------------------------------- //
void guAccelListBox::OnConfigUpdated( wxCommandEvent &event )
{
int Flags = event.GetInt();
if( Flags & guPREFERENCE_PAGE_FLAG_ACCELERATORS )
{
CreateAcceleratorTable();
}
}
// -------------------------------------------------------------------------------- //
| 2,387
|
C++
|
.cpp
| 53
| 42.792453
| 97
| 0.567126
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
750,636
|
ListView.cpp
|
anonbeat_guayadeque/src/ui/itemlistbox/ListView.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
#include "ListView.h"
#include "EventCommandIds.h"
#include "Config.h"
#include "Images.h"
#include "MainApp.h"
#include "MainFrame.h"
#include "OnlineLinks.h"
#include "Utils.h"
#include <wx/dcbuffer.h>
#include <wx/event.h>
#include <wx/renderer.h>
#include <wx/string.h>
#include <wx/checklst.h>
#include <wx/gdicmn.h>
#include <wx/font.h>
#include <wx/colour.h>
#include <wx/settings.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/icon.h>
#include <wx/bmpbuttn.h>
#include <wx/button.h>
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/dialog.h>
namespace Guayadeque {
#define guLISTVIEW_ITEM_MARGIN 2
#define guLISTVIEW_TIMER_TIMEOUT 1000
#define guLISTVIEW_MIN_COL_SIZE 20
#define guLISTVIEWHEADER_IMAGE_WIDTH 18
wxDEFINE_EVENT( guEVT_LISTBOX_ITEM_COL_CLICKED, wxListEvent );
wxDEFINE_EVENT( guEVT_LISTBOX_ITEM_COL_RCLICKED, wxListEvent );
WX_DEFINE_OBJARRAY( guListViewColumnArray )
static wxString FindChars = wxT( "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789 @&*+-_=/\\ºª:.,;çÇ<>$%()'\"|" );
// -------------------------------------------------------------------------------- //
// guListViewColEdit
// -------------------------------------------------------------------------------- //
class guListViewColEdit : public wxDialog
{
//private:
protected:
int m_SelItem;
guListView * m_Owner;
guListViewColumnArray * m_Columns;
wxArrayString m_ItemsText;
wxArrayInt m_ItemsData;
wxCheckListBox * m_ColumnsListBox;
wxBitmapButton * m_UpBitmapBtn;
wxBitmapButton * m_DownBitmapBtn;
void OnColumnSelected( wxCommandEvent &event );
void OnUpBtnClick( wxCommandEvent &event );
void OnDownBtnClick( wxCommandEvent &event );
public:
guListViewColEdit( wxWindow * parent, guListViewColumnArray * columns );
~guListViewColEdit();
void UpdateColumns( void );
};
// -------------------------------------------------------------------------------- //
// guListViewClientTimer
// -------------------------------------------------------------------------------- //
class guListViewClientTimer : public wxTimer
{
public:
guListViewClient * m_ListViewClient;
//
guListViewClientTimer( guListViewClient * listviewclient )
{
m_ListViewClient = listviewclient;
}
//Called each time the timer's timeout expires
void Notify();
};
// -------------------------------------------------------------------------------- //
// guListView
// -------------------------------------------------------------------------------- //
guListView::guListView( wxWindow * parent, const int flags, wxWindowID id, const wxPoint &pos, const wxSize &size, long style ) :
wxScrolledWindow( parent, id, pos, size, style )
{
m_Columns = new guListViewColumnArray();
m_ImageList = ( wxImageList * ) NULL;
m_ListBox = new guListViewClient( this, flags, m_Columns, &m_Attr );
if( !( flags & guLISTVIEW_HIDE_HEADER ) )
m_Header = new guListViewHeader( this, m_ListBox, m_Columns, wxPoint( 0, 0 ) );
else
m_Header = NULL;
m_ColSelect = ( flags & guLISTVIEW_COLUMN_SELECT );
m_AllowDrag = ( flags & guLISTVIEW_ALLOWDRAG );
m_AllowDrop = ( flags & guLISTVIEW_ALLOWDROP );
m_DragSelfItemsEnabled = ( flags & guLISTVIEW_DRAGSELFITEMS );
m_DragOverItem = wxNOT_FOUND;
m_LastDragOverItem = wxNOT_FOUND;
m_DragOverAfter = false;
m_LastDragOverAfter = false;
m_DragSelfItems = false;
if( m_AllowDrop )
{
SetDropTarget( new guListViewDropTarget( this ) );
}
parent->Bind( wxEVT_SIZE, &guListView::OnChangedSize, this );
m_ListBox->Bind( wxEVT_KEY_DOWN, &guListView::OnKeyDown, this );
Bind( wxEVT_CONTEXT_MENU, &guListView::OnContextMenu, this );
if( m_AllowDrag )
{
Bind( wxEVT_LIST_BEGIN_DRAG, &guListView::OnBeginDrag, this );
}
m_ListBox->Bind( wxEVT_LEFT_DOWN, &guListView::OnMouse, this );
m_ListBox->Bind( wxEVT_LEFT_UP, &guListView::OnMouse, this );
m_ListBox->Bind( wxEVT_MOTION, &guListView::OnMouse, this );
}
// -------------------------------------------------------------------------------- //
guListView::~guListView()
{
if( m_Columns )
delete m_Columns;
if( m_ImageList )
delete m_ImageList;
GetParent()->Unbind( wxEVT_SIZE, &guListView::OnChangedSize, this );
m_ListBox->Unbind( wxEVT_KEY_DOWN, &guListView::OnKeyDown, this );
Unbind( wxEVT_CONTEXT_MENU, &guListView::OnContextMenu, this );
if( m_AllowDrag )
{
Unbind( wxEVT_LIST_BEGIN_DRAG, &guListView::OnBeginDrag, this );
}
m_ListBox->Unbind( wxEVT_LEFT_DOWN, &guListView::OnMouse, this );
m_ListBox->Unbind( wxEVT_LEFT_UP, &guListView::OnMouse, this );
m_ListBox->Unbind( wxEVT_MOTION, &guListView::OnMouse, this );
}
// -------------------------------------------------------------------------------- //
void guListView::InsertColumn( guListViewColumn * column )
{
m_Columns->Add( column );
if( m_Header )
m_Header->RefreshWidth();
}
// -------------------------------------------------------------------------------- //
void guListView::OnChangedSize( wxSizeEvent &event )
{
int w;
int h = 0;
int d;
wxSize Size = event.GetSize();
//Size.x -= 4;
//Size.y -= 4;
//guLogMessage( wxT( "ListView SetSize %i,%i" ), Size.x, Size.y );
if( m_Header )
{
// Calculate the Height
GetTextExtent( wxT("Hg"), &w, &h, &d );
h += d + 4;
// Only change size if its different
if( m_Header->GetSize().GetWidth() != Size.x )
{
m_Header->SetSize( Size.x, h );
}
m_Header->RefreshWidth();
}
if( m_ListBox )
{
m_ListBox->SetSize( Size.x, Size.y - h );
m_ListBox->Move( 0, h );
}
// continue with default behaivor
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guListView::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
if( ( row == wxNOT_FOUND ) || ( row >= GetItemCount() ) )
return;
m_ListBox->DoDrawItem( dc, rect, row, col );
}
// -------------------------------------------------------------------------------- //
void guListView::DrawBackground( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
if( row == wxNOT_FOUND )
return;
m_ListBox->DoDrawBackground( dc, rect, row, col );
}
// -------------------------------------------------------------------------------- //
void guListView::OnContextMenu( wxContextMenuEvent& event )
{
wxMenu Menu;
CreateContextMenu( &Menu );
if( Menu.GetMenuItemCount() )
{
wxPoint Point = event.GetPosition();
// If from keyboard
if( Point.x == -1 && Point.y == -1 )
{
wxSize Size = GetSize();
Point.x = Size.x / 2;
Point.y = Size.y / 2;
}
else
{
Point = ScreenToClient( Point );
}
PopupMenu( &Menu, Point.x, Point.y );
}
}
// -------------------------------------------------------------------------------- //
void guListView::SetItemCount( const int count )
{
m_ListBox->SetItemCount( count );
if( m_Header )
m_Header->RefreshWidth();
}
// -------------------------------------------------------------------------------- //
wxCoord guListView::OnMeasureItem( size_t n ) const
{
// Code taken from the generic/listctrl.cpp file
guListView * self = wxConstCast( this, guListView );
wxClientDC dc( self );
dc.SetFont( GetFont() );
wxCoord y;
dc.GetTextExtent( wxT( "Hg" ), NULL, &y );
self->SetItemHeight( y + 4 ); // 2 up, 2 down
return y + 4;
}
// -------------------------------------------------------------------------------- //
void guListView::SetSelection( int selection )
{
m_ListBox->SetSelection( selection );
wxCommandEvent event( wxEVT_LISTBOX, m_ListBox->GetId() );
event.SetEventObject( m_ListBox );
event.SetInt( selection );
(void) GetEventHandler()->ProcessEvent( event );
}
// -------------------------------------------------------------------------------- //
void guListView::RefreshAll( int scrollto )
{
if( scrollto != wxNOT_FOUND )
{
if( !m_ListBox->IsVisible( scrollto ) )
{
m_ListBox->ScrollToRow( scrollto );
}
}
m_ListBox->RefreshAll();
}
// -------------------------------------------------------------------------------- //
void guListView::OnBeginDrag( wxCommandEvent &event )
{
guDataObjectComposite Files;
if( GetDragFiles( &Files ) )
{
wxDropSource source( Files, this );
m_DragSelfItems = true;
wxDragResult Result = source.DoDragDrop();
if( Result )
{
}
m_DragSelfItems = false;
m_DragOverItem = wxNOT_FOUND;
RefreshAll();
}
}
// -------------------------------------------------------------------------------- //
wxArrayInt guListView::GetSelectedItems( const bool convertall ) const
{
wxArrayInt RetVal;
unsigned long cookie;
int item;
int ItemId;
if( GetItemCount() )
{
if( m_ListBox->HasMultipleSelection() )
{
item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
ItemId = GetItemId( item );
RetVal.Add( ItemId );
if( convertall && ( ItemId == 0 ) )
break;
item = GetNextSelected( cookie );
}
}
else
{
item = m_ListBox->GetSelection();
if( item != wxNOT_FOUND )
{
ItemId = GetItemId( item );
RetVal.Add( ItemId );
}
}
//
if( convertall && ( RetVal.Index( 0 ) != wxNOT_FOUND ) )
{
RetVal.Empty();
int count = GetItemCount();
for( int index = 0; index < count; index++ )
{
RetVal.Add( GetItemId( index ) );
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayInt guListView::GetSelectedIndexs( const bool convertall ) const
{
wxArrayInt RetVal;
unsigned long cookie;
int item;
if( GetItemCount() )
{
if( m_ListBox->HasMultipleSelection() )
{
item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
RetVal.Add( item );
if( convertall && ( item == 0 ) )
break;
item = GetNextSelected( cookie );
}
}
else
{
item = m_ListBox->GetSelection();
if( item != wxNOT_FOUND )
{
RetVal.Add( item );
}
}
//
if( convertall && ( RetVal.Index( 0 ) != wxNOT_FOUND ) )
{
RetVal.Empty();
int count = GetItemCount();
for( int index = 0; index < count; index++ )
{
RetVal.Add( index );
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guListView::SetSelectedItems( const wxArrayInt &selection )
{
int Count = GetItemCount();
// TODO Need to speed up this
ClearSelectedItems();
if( Count && selection.Count() )
{
bool IsMultiple = m_ListBox->HasMultipleSelection();
for( int Index = 0; Index < Count; Index++ )
{
if( selection.Index( GetItemId( Index ) ) != wxNOT_FOUND )
{
if( IsMultiple )
Select( Index );
else
SetSelection( Index );
}
}
wxCommandEvent event( wxEVT_LISTBOX, m_ListBox->GetId() );
event.SetEventObject( m_ListBox );
event.SetInt( selection[ 0 ] );
(void) GetEventHandler()->ProcessEvent( event );
}
}
// -------------------------------------------------------------------------------- //
void guListView::SetSelectedIndexs( const wxArrayInt &selection )
{
// TODO Need to speed up this
ClearSelectedItems();
int ItemCount = GetItemCount();
if( ItemCount )
{
int Count;
if( ( Count = selection.Count() ) )
{
bool IsMultiple = m_ListBox->HasMultipleSelection();
for( int Index = 0; Index < Count; Index++ )
{
if( selection[ Index ] < ItemCount )
{
if( IsMultiple )
Select( selection[ Index ] );
else
SetSelection( selection[ Index ] );
}
}
wxCommandEvent event( wxEVT_LISTBOX, m_ListBox->GetId() );
event.SetEventObject( m_ListBox );
event.SetInt( selection[ 0 ] );
(void) GetEventHandler()->ProcessEvent( event );
}
}
}
// -------------------------------------------------------------------------------- //
void guListView::GetSelectedItems( guListItems * items, const bool convertall ) const
{
unsigned long cookie;
int item;
bool AppendAll = false;
int count = GetItemCount();
if( count )
{
if( m_ListBox->HasMultipleSelection() )
{
item = GetFirstSelected( cookie );
while( item != wxNOT_FOUND )
{
if( convertall && ( item == 0 ) )
{
AppendAll = true;
break;
}
items->Add( new guListItem( GetItemId( item ), GetItemName( item ) ) );
item = GetNextSelected( cookie );
}
}
else
{
item = m_ListBox->GetSelection();
if( item != wxNOT_FOUND )
{
items->Add( new guListItem( GetItemId( item ), GetItemName( item ) ) );
}
}
//
if( convertall && AppendAll )
{
for( int index = 0; index < count; index++ )
{
items->Add( new guListItem( GetItemId( index ), GetItemName( index ) ) );
}
}
}
}
// -------------------------------------------------------------------------------- //
void guListView::SetColumnWidth( const int col, const int width )
{
( * m_Columns )[ col ].m_Width = width;
if( m_Header )
m_Header->RefreshWidth();
}
// -------------------------------------------------------------------------------- //
void guListView::SetColumnLabel( const int col, const wxString &label )
{
m_Columns->Item( col ).m_Label = label;
if( m_Header )
m_Header->Refresh();
}
// -------------------------------------------------------------------------------- //
void guListView::SetColumnImage( const int col, const int imageindex )
{
m_Columns->Item( col ).m_ImageIndex = imageindex;
if( m_Header )
m_Header->Refresh();
}
// -------------------------------------------------------------------------------- //
void guListView::SetImageList( wxImageList * imagelist )
{
if( m_ImageList )
delete m_ImageList;
m_ImageList = imagelist;
if( m_Header )
m_Header->SetImageList( imagelist );
}
// -------------------------------------------------------------------------------- //
int guListView::GetDragFiles( guDataObjectComposite * files )
{
guTrackArray Tracks;
wxArrayString Filenames;
int Count = GetSelectedSongs( &Tracks, true );
for( int Index = 0; Index < Count; Index++ )
{
if( Tracks[ Index ].m_Offset )
continue;
Filenames.Add( guFileDnDEncode( Tracks[ Index ].m_FileName ) );
}
files->SetTracks( Tracks );
files->SetFiles( Filenames );
return Count;
}
// -------------------------------------------------------------------------------- //
void guListView::OnDragOver( wxCoord x, wxCoord y )
{
//guLogMessage( wxT( ">>guListView::OnDragOver( %u, %u )" ), x, y );
int HeaderHeight = 0;
if( m_Header )
{
HeaderHeight = m_Header->GetSize().GetHeight();
}
y -= HeaderHeight;
m_DragOverItem = HitTest( x, y );
if( ( int ) m_DragOverItem != wxNOT_FOUND )
{
int ItemHeight = m_ListBox->OnMeasureItem( m_DragOverItem );
m_DragOverAfter = ( y % ItemHeight ) > ( ItemHeight / 2 );
}
//guLogMessage( wxT( "Current: %i Last: %i" ), m_DragOverItem, m_LastDragOverItem );
if( ( m_DragOverItem != m_LastDragOverItem ) )
{
if( m_DragOverItem != wxNOT_FOUND )
RefreshRows( m_DragOverItem, m_DragOverItem );
if( m_LastDragOverItem != wxNOT_FOUND )
RefreshRows( m_LastDragOverItem, m_LastDragOverItem );
m_LastDragOverItem = m_DragOverItem;
}
else if( m_DragOverAfter != m_LastDragOverAfter )
{
RefreshRows( m_DragOverItem, m_DragOverItem );
m_LastDragOverAfter = m_DragOverAfter;
}
// Scroll items if we are in the top or bottom borders
int Width;
int Height;
GetSize( &Width, &Height );
Height -= HeaderHeight;
int Rows = 0;
if( ( y > ( Height - 10 ) ) && ( int ) GetVisibleRowsEnd() != GetItemCount() )
{
Rows = 1;
}
else
{
if( ( y < 10 ) && ( GetVisibleRowsBegin() > 0 ) )
{
Rows = -1;
}
}
//guLogMessage( wxT( "ScrollLines %i, %i, %i" ), Height, (int) y, Rows );
//guLogMessage( wxT( "End: %li Items:%i" ), GetVisibleRowsEnd(), GetItemCount() );
if( Rows )
ScrollRows( Rows );
}
// -------------------------------------------------------------------------------- //
void guListView::OnMouse( wxMouseEvent &event )
{
if( event.Dragging() )
{
if( !m_DragCount )
{
m_DragStart = event.GetPosition();
}
if( ++m_DragCount == 3 )
{
wxListEvent le( wxEVT_LIST_BEGIN_DRAG, GetId() );
le.SetEventObject( this );
le.m_pointDrag = m_DragStart;
GetEventHandler()->ProcessEvent( le );
}
return;
}
else
{
m_DragCount = 0;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
int FindColumnId( const guListViewColumnArray * columns, const int id )
{
int count = columns->Count();
for( int index = 0; index < count; index++ )
{
if( ( * columns )[ index ].m_Id == id )
return index;
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
bool guListView::GetColumnData( const int id, int * index, int * width, bool * enabled )
{
int ColPos = FindColumnId( m_Columns, id );
if( ColPos != wxNOT_FOUND )
{
* index = ColPos;
* width = ( * m_Columns )[ ColPos ].m_Width;
* enabled = ( * m_Columns )[ ColPos ].m_Enabled;
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
bool guListView::SetColumnData( const int id, const int index, const int width, const bool enabled, const bool refresh )
{
int ColPos = FindColumnId( m_Columns, id );
if( ColPos != wxNOT_FOUND )
{
if( ColPos != index )
{
guListViewColumn * Column = m_Columns->Detach( ColPos );
m_Columns->Insert( Column, index );
}
( * m_Columns )[ index ].m_Width = width;
( * m_Columns )[ index ].m_Enabled = enabled;
if( refresh )
{
m_Header->RefreshWidth();
Refresh();
}
return true;
}
return false;
}
// -------------------------------------------------------------------------------- //
// guListViewClient
// -------------------------------------------------------------------------------- //
BEGIN_EVENT_TABLE(guListViewClient,wxVListBox)
EVT_PAINT (guListViewClient::OnPaint)
EVT_MOUSE_EVENTS (guListViewClient::OnMouse)
EVT_SCROLLWIN (guListViewClient::OnHScroll)
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guListViewClient::guListViewClient( wxWindow * parent, const int flags,
guListViewColumnArray * columns, guListViewAttr * attr ) :
wxVListBox( parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, flags|wxHSCROLL|wxVSCROLL|wxNO_BORDER )
{
m_Owner = ( guListView * ) parent;
m_SearchStrTimer = new guListViewClientTimer( this );
m_Attr = attr;
m_Columns = columns;
m_SearchStr = wxEmptyString;
m_ItemHeight = wxNOT_FOUND;
m_HScrollPos = 0;
m_MouseWasLeftUp = false;
m_MouseSelecting = false;
m_ColumnClickEvents = ( flags & guLISTVIEW_COLUMN_CLICK_EVENTS );
SetBackgroundColour( m_Attr->m_EveBgColor );
Bind( wxEVT_KEY_DOWN, &guListViewClient::OnKeyDown, this );
}
// -------------------------------------------------------------------------------- //
guListViewClient::~guListViewClient()
{
if( m_SearchStrTimer )
delete m_SearchStrTimer;
Unbind( wxEVT_KEY_DOWN, &guListViewClient::OnKeyDown, this );
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnMouse( wxMouseEvent &event )
{
int MouseX = event.m_x;
int MouseY = event.m_y;
int Item = HitTest( MouseX, MouseY );
bool ResetVals = false;
// We want to get a better experience for dragging as before
// when you click over selected items the items was unselected
// even when you tried to drag then.
// Here we check if the item was selected and if so wait for the button up
// to unselecte the item
//guLogMessage( wxT( "ID: %u LD: %i LU: %i SD: %i CD: %i WasLeftUp: %i Selecting: %i " ), event.GetId(), event.LeftDown(), event.LeftUp(), event.ShiftDown(), event.ControlDown(), m_MouseWasLeftUp, m_MouseSelecting );
if( !m_MouseWasLeftUp && !event.ShiftDown() && !event.ControlDown() )
{
m_MouseWasLeftUp = event.LeftUp();
if( ( event.LeftDown() || m_MouseWasLeftUp ) )
{
if( Item != wxNOT_FOUND )
{
bool Selected = IsSelected( Item );
if( Selected )
{
if( !m_MouseSelecting && event.LeftUp() )
{
// Its a LeftUp event
event.SetEventType( wxEVT_LEFT_DOWN );
event.m_leftDown = true;
AddPendingEvent( event );
}
return;
}
m_MouseSelecting = event.LeftDown();
}
}
else
{
ResetVals = true;
}
}
else
{
ResetVals = true;
}
// Only when the left or right is down and the click events are enabled
if( m_ColumnClickEvents &&
( Item != wxNOT_FOUND ) &&
( ( event.LeftDown() && !( ResetVals && m_MouseSelecting ) ) || event.RightDown() ) )
{
// We want get the left click events, calculate which column clicked on and
// send a Column_Clicked event
int Col_Num = wxNOT_FOUND;
MouseX += GetScrollPos( wxHORIZONTAL );
int Col_Start = 0;
int Col_Border = 0;
int Count = m_Columns->Count();
for( int Index = 0; Index < Count; Index++ )
{
if( ( * m_Columns )[ Index ].m_Enabled )
{
Col_Border += ( * m_Columns )[ Index ].m_Width;
if( MouseX < Col_Border )
{
Col_Num = Index;
break;
}
Col_Start = Col_Border;
}
}
if( Col_Num != wxNOT_FOUND )
{
wxListEvent le( event.LeftDown() ? guEVT_LISTBOX_ITEM_COL_CLICKED :
guEVT_LISTBOX_ITEM_COL_RCLICKED, m_Owner->GetId() );
le.SetEventObject( m_Owner );
le.m_pointDrag.x = MouseX - Col_Start;
le.m_pointDrag.y = MouseY;
le.SetInt( Item );
le.m_col = Col_Num;
m_Owner->GetEventHandler()->ProcessEvent( le );
//guLogMessage( wxT( "Col %i have been clicked (%i-%i) %i-%i" ), Col_Num, Col_Start, Col_Border, MouseX - Col_Start, MouseY );
//return;
}
}
// The wxVListBox dont handle the right click to select items. We add this functionality
if( event.RightDown() && ( Item != wxNOT_FOUND ) && !IsSelected( Item ) )
OnLeftDown( event );
if( ResetVals )
{
m_MouseWasLeftUp = false;
m_MouseSelecting = false;
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnKeyDown( wxKeyEvent &event )
{
wxChar KeyChar = event.GetKeyCode();
int KeyMod = event.GetModifiers();
if( KeyMod == wxMOD_NONE || KeyMod == wxMOD_SHIFT )
{
if( FindChars.Find( KeyChar ) != wxNOT_FOUND )
{
if( m_SearchStrTimer->IsRunning() )
{
m_SearchStrTimer->Stop();
}
m_SearchStrTimer->Start( guLISTVIEW_TIMER_TIMEOUT, wxTIMER_ONE_SHOT );
m_SearchStr.Append( KeyChar );
return;
}
else if( ( event.GetKeyCode() == WXK_RETURN ) || ( event.GetKeyCode() == WXK_NUMPAD_ENTER ) )
{
if( GetSelectedCount() )
{
unsigned long Cookie;
wxCommandEvent DCEvent( wxEVT_LISTBOX_DCLICK, GetId() );
DCEvent.SetEventObject( this );
DCEvent.SetInt( GetFirstSelected( Cookie ) );
( void ) GetEventHandler()->ProcessEvent( DCEvent );
}
}
}
else if( KeyMod == wxMOD_CONTROL )
{
if( KeyChar == 'a' || KeyChar == 'A' )
{
SelectAll();
wxCommandEvent evt( wxEVT_LISTBOX, GetId() );
evt.SetEventObject( this );
evt.SetInt( 0 );
(void) GetEventHandler()->ProcessEvent( evt );
return;
}
}
event.Skip();
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnPaint( wxPaintEvent &event )
{
// CODE FROM THE wxVListBox class
wxSize clientSize = GetClientSize();
wxAutoBufferedPaintDC dc( this );
// the update rectangle
wxRect rectUpdate = GetUpdateClientRect();
// fill it with background colour
dc.SetBackground( GetBackgroundColour() );
dc.Clear();
AdjustDC( dc );
// the bounding rectangle of the current line
wxRect rectLine;
rectLine.width = clientSize.x;
m_Owner->ItemsLock();
const size_t lineMax = GetVisibleEnd();
size_t line = GetVisibleRowsBegin();
m_Owner->ItemsCheckRange( line, lineMax );
// iterate over all visible lines
for( ; line < lineMax; line++ )
{
const wxCoord hLine = OnGetRowHeight( line );
rectLine.height = hLine;
// and draw the ones which intersect the update rect
if( rectLine.Intersects( rectUpdate ) )
{
// don't allow drawing outside of the lines rectangle
wxDCClipper clip(dc, rectLine);
wxRect rect = rectLine;
OnDrawBackground(dc, rect, line);
OnDrawSeparator(dc, rect, line);
//rect.Deflate(m_ptMargins.x, m_ptMargins.y);
OnDrawItem( dc, rect, line );
}
else // no intersection
{
if ( rectLine.GetTop() > rectUpdate.GetBottom() )
{
// we are already below the update rect, no need to continue
// further
break;
}
//else: the next line may intersect the update rect
}
rectLine.y += hLine;
}
m_Owner->ItemsUnlock();
}
// -------------------------------------------------------------------------------- //
void guListViewClient::DoDrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
dc.SetFont( * m_Attr->m_Font );
dc.SetBackgroundMode( wxTRANSPARENT );
dc.SetTextForeground( IsSelected( row ) ? m_Attr->m_SelFgColor : m_Attr->m_TextFgColor );
dc.DrawText( m_Owner->OnGetItemText( row, col ),
rect.x + guLISTVIEW_ITEM_MARGIN, rect.y + guLISTVIEW_ITEM_MARGIN );
}
// -------------------------------------------------------------------------------- //
void guListViewClient::DrawItem( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
m_Owner->DrawItem( dc, rect, row, col );
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnDrawItem( wxDC &dc, const wxRect &rect, size_t n ) const
{
if( ( int ) n == wxNOT_FOUND )
return;
wxRect cRect = rect;
int StartOfs = rect.x;
int count = m_Columns->Count();
for( int index = 0; index < count; index++ )
{
if( ( * m_Columns )[ index ].m_Enabled )
{
int w = ( * m_Columns )[ index ].m_Width;
if( w == wxNOT_FOUND )
w = rect.width;
cRect.x = StartOfs;
cRect.width = w - guLISTVIEW_ITEM_MARGIN;
{
wxDCClipper clip( dc, cRect );
DrawItem( dc, cRect, n, index );
}
StartOfs += w;
if( StartOfs > ( m_HScrollPos + rect.width ) )
break;
}
}
}
// -------------------------------------------------------------------------------- //
void guListViewClient::SetItemHeigth( const int height )
{
m_ItemHeight = height;
}
// -------------------------------------------------------------------------------- //
wxCoord guListViewClient::OnMeasureItem( size_t n ) const
{
if( m_ItemHeight != wxNOT_FOUND )
{
return m_ItemHeight;
}
else
{
return m_Owner->OnMeasureItem( n );
}
}
// -------------------------------------------------------------------------------- //
void guListViewClient::DoDrawBackground( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
wxRect LineRect;
if( IsSelected( row ) )
dc.SetBrush( wxBrush( m_Attr->m_SelBgColor ) );
else if( row == ( int ) m_Owner->m_DragOverItem )
dc.SetBrush( m_Attr->m_DragBgColor );
else
dc.SetBrush( wxBrush( row & 1 ? m_Attr->m_OddBgColor : m_Attr->m_EveBgColor ) );
dc.SetPen( * wxTRANSPARENT_PEN );
dc.DrawRectangle( rect );
if( row == ( int ) m_Owner->m_DragOverItem )
{
LineRect = rect;
if( m_Owner->m_DragOverAfter )
LineRect.y += ( LineRect.height - 2 );
LineRect.height = 2;
dc.SetBrush( * wxBLACK_BRUSH );
dc.DrawRectangle( LineRect );
}
}
// -------------------------------------------------------------------------------- //
void guListViewClient::DrawBackground( wxDC &dc, const wxRect &rect, const int row, const int col ) const
{
m_Owner->DrawBackground( dc, rect, row, col );
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnDrawBackground( wxDC &dc, const wxRect &rect, size_t n ) const
{
if( ( int ) n == wxNOT_FOUND )
return;
wxRect cRect = rect;
int StartOfs = rect.x;
int count = m_Columns->Count();
for( int index = 0; index < count; index++ )
{
if( ( * m_Columns )[ index ].m_Enabled )
{
cRect.x = StartOfs;
int w = ( * m_Columns )[ index ].m_Width;
if( w != wxNOT_FOUND )
cRect.width = w;
{
wxDCClipper clip( dc, cRect );
DrawBackground( dc, cRect, n, index );
}
StartOfs += cRect.width;
if( StartOfs > ( m_HScrollPos + rect.width ) )
break;
}
}
}
// -------------------------------------------------------------------------------- //
wxString guListViewClient::GetItemSearchText( const int row )
{
return m_Owner->GetItemSearchText( row );
}
// -------------------------------------------------------------------------------- //
long guListViewClient::FindItem( long start, const wxString& str, bool partial, bool atstart )
{
if( str.empty() )
return wxNOT_FOUND;
long pos = start;
wxString str_upper = str.Upper();
if( pos < 0 )
pos = 0;
int count = GetItemCount();
for( int index = pos; index < count; index++ )
{
wxString line_upper = GetItemSearchText( index ).Upper();
if( !partial )
{
if( line_upper == str_upper )
return index;
}
else if( atstart )
{
if( line_upper.Find( str_upper ) == 0 )
return index;
}
else
{
if( line_upper.Find( str_upper ) != wxNOT_FOUND )
return index;
}
}
return wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
void guListViewClient::OnHScroll( wxScrollWinEvent &event )
{
if( event.GetOrientation() == wxHORIZONTAL )
{
m_HScrollPos = event.GetPosition();
m_Owner->Update();
m_Owner->Refresh();
}
else
{
event.Skip();
}
}
// -------------------------------------------------------------------------------- //
void guListViewClient::SetHScrollbar( const int width )
{
if( width )
SetScrollbar( wxHORIZONTAL, m_HScrollPos, 125, width + 125 );
else
SetScrollbar( wxHORIZONTAL, 0, 0, 0 );
}
// -------------------------------------------------------------------------------- //
void guListViewClient::SetScrollPos( int orientation, int pos, bool refresh )
{
if( orientation == wxHORIZONTAL )
{
m_HScrollPos = pos;
}
wxVListBox::SetScrollPos( orientation, pos, refresh );
}
// -------------------------------------------------------------------------------- //
//int guListViewClient::GetHScrollPosition( void )
//{
// return m_HScrollPos;
//}
// -------------------------------------------------------------------------------- //
void guListViewClient::AdjustDC( wxDC &dc )
{
int org_x = 0;
int org_y = 0;
dc.GetDeviceOrigin( &org_x, &org_y );
dc.SetDeviceOrigin( org_x - m_HScrollPos, org_y );
}
// -------------------------------------------------------------------------------- //
// guListViewHeader
// -------------------------------------------------------------------------------- //
BEGIN_EVENT_TABLE(guListViewHeader,wxWindow)
EVT_PAINT (guListViewHeader::OnPaint)
EVT_MOUSE_EVENTS (guListViewHeader::OnMouse)
EVT_SET_FOCUS (guListViewHeader::OnSetFocus)
EVT_MOUSE_CAPTURE_LOST (guListViewHeader::OnCaptureLost)
END_EVENT_TABLE()
// -------------------------------------------------------------------------------- //
guListViewHeader::guListViewHeader()
{
m_Owner = (guListView *) NULL;
m_ListViewClient = ( guListViewClient * ) NULL;
m_Columns = (guListViewColumnArray*) NULL;
m_ResizeCursor = new wxCursor( wxCURSOR_SIZEWE );
m_IsDragging = wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
guListViewHeader::guListViewHeader( wxWindow * parent, guListViewClient * owner,
guListViewColumnArray * columns, const wxPoint& pos, const wxSize& size )
: wxWindow( parent, wxID_ANY, pos, size )
{
m_Owner = ( guListView * ) parent;
m_ListViewClient = owner;
m_Columns = columns;
m_ResizeCursor = new wxCursor( wxCURSOR_SIZEWE );
m_IsDragging = wxNOT_FOUND;
}
// -------------------------------------------------------------------------------- //
guListViewHeader::~guListViewHeader()
{
if( m_ResizeCursor )
delete m_ResizeCursor;
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::OnPaint( wxPaintEvent &event )
{
wxPaintDC dc( this );
AdjustDC( dc );
dc.SetFont( GetFont() );
// width and height of the entire header window
int w, h;
GetClientSize( &w, &h );
dc.SetBackgroundMode( wxTRANSPARENT );
dc.SetTextForeground( GetForegroundColour() );
int flags = 0;
if( !m_parent->IsEnabled() )
flags |= wxCONTROL_DISABLED;
wxCoord wLabel;
wxCoord hLabel;
dc.GetTextExtent( wxT( "hg" ), &wLabel, &hLabel );
hLabel = ( h / 2 ) - ( hLabel / 2 );
int count = m_Columns->Count();
wxRect cRect = wxRect( 0, 0, w, h );
int StartOfs = 0;
int ScrollPos = m_ListViewClient->GetScrollPos( wxHORIZONTAL );
for( int index = 0; index < count; index++ )
{
guListViewColumn * CurCol = &m_Columns->Item( index );
if( CurCol->m_Enabled )
{
cRect.x = StartOfs;
int cw = CurCol->m_Width;
if( cw != wxNOT_FOUND )
cRect.width = cw;
//guLogMessage( wxT( "Pinting header %u at %u %u '%s'" ), index, cRect.x, cRect.width, ( * m_Columns )[ index ].m_Label.c_str() );
wxRendererNative::Get().DrawHeaderButton( this, dc, cRect, flags );
if( CurCol->m_ImageIndex >= 0 )
cRect.width -= guLISTVIEWHEADER_IMAGE_WIDTH;
dc.SetClippingRegion( cRect );
dc.DrawText( CurCol->m_Label, cRect.x + 4, hLabel );
dc.DestroyClippingRegion();
if( CurCol->m_ImageIndex >= 0 )
{
dc.DrawBitmap( m_ImageList->GetBitmap( CurCol->m_ImageIndex ), cRect.x + cRect.width + 1, ( cRect.height / 2 ) - 8, true );
}
StartOfs += CurCol->m_Width;
if( StartOfs > w + ScrollPos )
break;
}
}
if( m_Width < w )
{
cRect.x = m_Width;
cRect.width = w - m_Width;
wxRendererNative::Get().DrawHeaderButton( this, dc, cRect, flags );
}
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::OnCaptureLost( wxMouseCaptureLostEvent &event )
{
m_IsDragging = false;
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::OnMouse( wxMouseEvent &event )
{
// we want to work with logical coords
int mx;
int hit_border = wxNOT_FOUND;
int col_num = wxNOT_FOUND;
int ScrollPos = m_ListViewClient->GetScrollPos( wxHORIZONTAL );
mx = event.GetX() + ScrollPos;
int my = event.GetY();
int col_border = 0;
int col_start = 0;
int count = m_Columns->Count();
for( int index = 0; index < count; index++ )
{
if( ( * m_Columns )[ index ].m_Enabled )
{
col_border += ( * m_Columns )[ index ].m_Width;
if( ( my < 22 ) && abs( mx - col_border ) < 3 )
{
hit_border = index;
break;
}
if( mx < col_border + 3 )
{
col_num = index;
break;
}
col_start = col_border;
}
}
// guLogMessage( wxT( "cn:%i cs:%i cb:%i id:%i mx:%i my:%i" ), col_num, col_start, col_border, m_IsDragging, mx, my );
//
if( m_IsDragging >= 0 )
{
if( event.LeftUp() )
{
m_IsDragging = wxNOT_FOUND;
ReleaseMouse();
}
else
{
//guLogMessage( wxT( "sp: %i mx:%i do:%i" ), ScrollPos, mx, m_DragOfset );
if( mx > ( m_DragOfset + guLISTVIEW_MIN_COL_SIZE ) )
{
m_Owner->SetColumnWidth( m_IsDragging, mx - m_DragOfset );
m_Owner->Refresh();
}
}
}
else if( event.LeftDown() || event.RightDown() )
{
if( event.LeftDown() && ( hit_border >= 0 ) ) // hit a border
{
m_IsDragging = hit_border;
m_DragOfset = col_start;
CaptureMouse();
}
else if( m_Owner->IsAllowedColumnSelect() && event.RightDown() )
{
OnEditColumns();
}
else if( col_num >= 0 )
{
wxListEvent le( event.LeftDown() ? wxEVT_LIST_COL_CLICK :
wxEVT_LIST_COL_RIGHT_CLICK, m_Owner->GetId() );
le.SetEventObject( m_Owner );
le.m_pointDrag = event.GetPosition();
le.m_pointDrag.y -= GetSize().y;
le.m_col = col_num;
m_Owner->GetEventHandler()->ProcessEvent( le );
//guLogMessage( wxT( "Col %i have been clicked %i" ), col_num,
// ( * m_Columns )[ col_num ].m_Width );
}
}
else if( event.Moving() )
{
m_IsDragging = wxNOT_FOUND;
if( hit_border >= 0 )
{
SetCursor( * m_ResizeCursor );
}
else
{
SetCursor( * wxSTANDARD_CURSOR );
}
}
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::OnSetFocus( wxFocusEvent &WXUNUSED(event) )
{
if( m_ListViewClient )
{
m_ListViewClient->SetFocus();
m_ListViewClient->Update();
}
}
// -------------------------------------------------------------------------------- //
int guListViewHeader::RefreshWidth( void )
{
// width and height of the entire header window
int w, h;
m_ListViewClient->GetClientSize( &w, &h );
int count = m_Columns->Count();
if( count > 1 )
{
m_Width = 0;
for( int index = 0; index < count; index++ )
{
if( ( * m_Columns )[ index ].m_Enabled )
{
m_Width += ( * m_Columns )[ index ].m_Width;
}
}
// Checkif its needed the horizontal scroll bar
if( m_Width > w )
{
//guLogMessage( wxT( "Vertical ScrollBar... %i %i %i %i %i" ), m_Width, w, m_Width - w,
// m_ListViewClient->GetScrollPos( wxHORIZONTAL ), ( h / m_ListViewClient->OnGetLineHeight( 0 ) ) );
if( m_ListViewClient->GetScrollPos( wxHORIZONTAL ) > m_Width - w )
{
m_ListViewClient->SetScrollPos( wxHORIZONTAL, m_Width - w );
}
m_ListViewClient->SetHScrollbar( m_Width - w );
}
else
{
m_ListViewClient->SetHScrollbar( 0 );
}
}
else
{
m_Width = w;
}
return m_Width;
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::AdjustDC( wxDC &dc )
{
int ScrollPos = m_ListViewClient->GetScrollPos( wxHORIZONTAL );
int org_x = 0;
int org_y = 0;
dc.GetDeviceOrigin( &org_x, &org_y );
dc.SetDeviceOrigin( org_x - ScrollPos, org_y );
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::OnEditColumns( void )
{
guListViewColEdit * ListViewColEdit = new guListViewColEdit( m_Owner, m_Columns );
if( ListViewColEdit )
{
if( ListViewColEdit->ShowModal() == wxID_OK )
{
ListViewColEdit->UpdateColumns();
RefreshWidth();
m_Owner->Refresh();
}
ListViewColEdit->Destroy();
}
}
// -------------------------------------------------------------------------------- //
void guListViewHeader::SetImageList( wxImageList * imagelist )
{
m_ImageList = imagelist;
}
// -------------------------------------------------------------------------------- //
// guListViewColEdit
// -------------------------------------------------------------------------------- //
guListViewColEdit::guListViewColEdit( wxWindow * parent, guListViewColumnArray * columns ) :
wxDialog( parent, wxID_ANY, _( "Select Columns" ), wxDefaultPosition, wxSize( 246,340 ), wxDEFAULT_DIALOG_STYLE )
{
m_Owner = ( guListView * ) parent;
m_Columns = columns;
m_SelItem = wxNOT_FOUND;
SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer * MainSizer;
MainSizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer * ColumnsSizer;
ColumnsSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _(" Columns ") ), wxHORIZONTAL );
int count = columns->Count();
for( int index = 0; index < count; index++ )
{
m_ItemsText.Add( ( * columns )[ index ].m_Label );
m_ItemsData.Add( ( * columns )[ index ].m_Id );
}
m_ColumnsListBox = new wxCheckListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_ItemsText, wxLB_SINGLE );
ColumnsSizer->Add( m_ColumnsListBox, 1, wxEXPAND|wxALL, 5 );
wxBoxSizer * BtnsSizer;
BtnsSizer = new wxBoxSizer( wxVERTICAL );
m_UpBitmapBtn = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_up ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_UpBitmapBtn->Enable( false );
BtnsSizer->Add( m_UpBitmapBtn, 0, wxTOP|wxBOTTOM, 5 );
m_DownBitmapBtn = new wxBitmapButton( this, wxID_ANY, guImage( guIMAGE_INDEX_down ), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW );
m_DownBitmapBtn->Enable( false );
BtnsSizer->Add( m_DownBitmapBtn, 0, wxTOP|wxBOTTOM, 5 );
ColumnsSizer->Add( BtnsSizer, 0, wxEXPAND, 5 );
wxStdDialogButtonSizer * StdBtnSizer;
wxButton * StdBtnSizerOK;
wxButton * StdBtnSizerCancel;
MainSizer->Add( ColumnsSizer, 1, wxEXPAND|wxALL, 5 );
StdBtnSizer = new wxStdDialogButtonSizer();
StdBtnSizerOK = new wxButton( this, wxID_OK );
StdBtnSizer->AddButton( StdBtnSizerOK );
StdBtnSizerCancel = new wxButton( this, wxID_CANCEL );
StdBtnSizer->AddButton( StdBtnSizerCancel );
StdBtnSizer->SetAffirmativeButton( StdBtnSizerOK );
StdBtnSizer->SetCancelButton( StdBtnSizerCancel );
StdBtnSizer->Realize();
MainSizer->Add( StdBtnSizer, 0, wxEXPAND|wxALL, 5 );
this->SetSizer( MainSizer );
this->Layout();
StdBtnSizerOK->SetDefault();
count = columns->Count();
for( int index = 0; index < count; index++ )
{
if( ( * columns )[ index ].m_Enabled )
{
m_ColumnsListBox->Check( index );
}
}
// Bind Events
m_ColumnsListBox->Bind( wxEVT_LISTBOX, &guListViewColEdit::OnColumnSelected, this );
m_UpBitmapBtn->Bind( wxEVT_BUTTON, &guListViewColEdit::OnUpBtnClick, this );
m_DownBitmapBtn->Bind( wxEVT_BUTTON, &guListViewColEdit::OnDownBtnClick, this );
m_ColumnsListBox->SetFocus();
}
// -------------------------------------------------------------------------------- //
guListViewColEdit::~guListViewColEdit()
{
// Unbind Events
m_ColumnsListBox->Unbind( wxEVT_LISTBOX, &guListViewColEdit::OnColumnSelected, this );
m_UpBitmapBtn->Unbind( wxEVT_BUTTON, &guListViewColEdit::OnUpBtnClick, this );
m_DownBitmapBtn->Unbind( wxEVT_BUTTON, &guListViewColEdit::OnDownBtnClick, this );
}
// -------------------------------------------------------------------------------- //
void guListViewColEdit::UpdateColumns( void )
{
int ColId;
int ColPos;
int count = m_ItemsData.Count();
for( int index = 0; index < count; index++ )
{
ColId = m_ItemsData[ index ];
ColPos = FindColumnId( m_Columns, ColId );
if( ColPos != index )
{
guListViewColumn * Column = m_Columns->Detach( ColPos );
m_Columns->Insert( Column, index );
}
( * m_Columns )[ index ].m_Enabled = m_ColumnsListBox->IsChecked( index );
}
}
// -------------------------------------------------------------------------------- //
void guListViewColEdit::OnColumnSelected( wxCommandEvent &event )
{
m_SelItem = event.GetInt();
if( m_SelItem != wxNOT_FOUND )
{
m_UpBitmapBtn->Enable( m_SelItem > 0 );
m_DownBitmapBtn->Enable( m_SelItem < ( int ) ( m_ItemsData.Count() - 1 ) );
}
else
{
m_UpBitmapBtn->Enable( false );
m_DownBitmapBtn->Enable( false );
}
}
// -------------------------------------------------------------------------------- //
void guListViewColEdit::OnUpBtnClick( wxCommandEvent &event )
{
wxString CurLabel = m_ItemsText[ m_SelItem ];
int CurData = m_ItemsData[ m_SelItem ];
bool CurCheck = m_ColumnsListBox->IsChecked( m_SelItem );
m_ColumnsListBox->SetString( m_SelItem, m_ColumnsListBox->GetString( m_SelItem - 1 ) );
m_ColumnsListBox->Check( m_SelItem, m_ColumnsListBox->IsChecked( m_SelItem - 1 ) );
m_ItemsText[ m_SelItem ] = m_ItemsText[ m_SelItem - 1 ];
m_ItemsData[ m_SelItem ] = m_ItemsData[ m_SelItem - 1 ];
m_SelItem--;
m_ColumnsListBox->SetString( m_SelItem, CurLabel );
if( CurCheck )
m_ColumnsListBox->Check( m_SelItem );
m_ItemsText[ m_SelItem ] = CurLabel;
m_ItemsData[ m_SelItem ] = CurData;
m_ColumnsListBox->SetSelection( m_SelItem );
event.SetInt( m_SelItem );
OnColumnSelected( event );
}
// -------------------------------------------------------------------------------- //
void guListViewColEdit::OnDownBtnClick( wxCommandEvent &event )
{
wxString CurLabel = m_ItemsText[ m_SelItem ];
int CurData = m_ItemsData[ m_SelItem ];
bool CurCheck = m_ColumnsListBox->IsChecked( m_SelItem );
m_ColumnsListBox->SetString( m_SelItem, m_ColumnsListBox->GetString( m_SelItem + 1 ) );
m_ColumnsListBox->Check( m_SelItem, m_ColumnsListBox->IsChecked( m_SelItem + 1 ) );
m_ItemsText[ m_SelItem ] = m_ItemsText[ m_SelItem + 1 ];
m_ItemsData[ m_SelItem ] = m_ItemsData[ m_SelItem + 1 ];
m_SelItem++;
m_ColumnsListBox->SetString( m_SelItem, CurLabel );
if( CurCheck )
m_ColumnsListBox->Check( m_SelItem );
m_ItemsText[ m_SelItem ] = CurLabel;
m_ItemsData[ m_SelItem ] = CurData;
m_ColumnsListBox->SetSelection( m_SelItem );
event.SetInt( m_SelItem );
OnColumnSelected( event );
}
// -------------------------------------------------------------------------------- //
// guListViewClientTimer
// -------------------------------------------------------------------------------- //
void guListViewClientTimer::Notify()
{
int index;
if( m_ListViewClient->m_SearchStr.Len() )
{
m_ListViewClient->SetSelection( -1 );
index = m_ListViewClient->FindItem( 0, m_ListViewClient->m_SearchStr, true );
m_ListViewClient->SetSelection( index );
wxCommandEvent event( wxEVT_LISTBOX, m_ListViewClient->GetId() );
event.SetEventObject( m_ListViewClient );
event.SetInt( index );
m_ListViewClient->ProcessEvent( event );
m_ListViewClient->m_SearchStr = wxEmptyString;
}
}
// -------------------------------------------------------------------------------- //
// guListViewDropFilesThread
// -------------------------------------------------------------------------------- //
guListViewDropFilesThread::guListViewDropFilesThread( guListViewDropTarget * playlistdroptarget,
guListView * listview, const wxArrayString &files ) :
wxThread()
{
m_ListView = listview;
m_Files = files;
m_ListViewDropTarget = playlistdroptarget;
if( Create() == wxTHREAD_NO_ERROR )
{
SetPriority( WXTHREAD_DEFAULT_PRIORITY );
Run();
}
}
// -------------------------------------------------------------------------------- //
guListViewDropFilesThread::~guListViewDropFilesThread()
{
// printf( "guListViewDropFilesThread Object destroyed\n" );
if( !TestDestroy() )
{
m_ListViewDropTarget->ClearPlayListFilesThread();
}
}
// -------------------------------------------------------------------------------- //
void guListViewDropFilesThread::AddDropFiles( const wxString &dirname )
{
wxDir Dir;
wxString FileName;
//wxString SavedDir( wxGetCwd() );
if( wxDirExists( dirname ) )
{
wxString DirName = dirname;
if( !DirName.EndsWith( wxT( "/" ) ) )
DirName += wxT( "/" );
Dir.Open( DirName );
if( Dir.IsOpened() )
{
if( !TestDestroy() && Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
{
do {
if( ( FileName[ 0 ] != '.' ) )
{
if( Dir.Exists( DirName + FileName ) )
{
AddDropFiles( DirName + FileName );
}
else
{
m_ListView->OnDropFile( DirName + FileName );
}
}
} while( Dir.GetNext( &FileName ) && !TestDestroy() );
}
}
}
else
{
m_ListView->OnDropFile( dirname );
}
}
// -------------------------------------------------------------------------------- //
guListViewDropFilesThread::ExitCode guListViewDropFilesThread::Entry()
{
int Count = m_Files.Count();
for( int index = 0; index < Count; ++index )
{
if( TestDestroy() )
return 0;
AddDropFiles( m_Files[ index ] );
}
m_ListView->OnDropEnd();
//
m_ListView->m_DragOverItem = wxNOT_FOUND;
return 0;
}
// -------------------------------------------------------------------------------- //
// guListViewDropTarget
// -------------------------------------------------------------------------------- //
guListViewDropTarget::guListViewDropTarget( guListView * listview ) : wxDropTarget()
{
m_ListView = listview;
m_ListViewDropFilesThread = NULL;
wxDataObjectComposite * DataObject = new wxDataObjectComposite();
wxCustomDataObject * TracksDataObject = new wxCustomDataObject( wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) );
DataObject->Add( TracksDataObject, true );
wxFileDataObject * FileDataObject = new wxFileDataObject();
DataObject->Add( FileDataObject, false );
SetDataObject( DataObject );
}
// -------------------------------------------------------------------------------- //
guListViewDropTarget::~guListViewDropTarget()
{
// printf( "guListViewDropTarget Object destroyed\n" );
}
// -------------------------------------------------------------------------------- //
wxDragResult guListViewDropTarget::OnData( wxCoord x, wxCoord y, wxDragResult def )
{
//guLogMessage( wxT( "guListViewDropTarget::OnData" ) );
if( def == wxDragError || def == wxDragNone || def == wxDragCancel )
return def;
if( m_ListView->m_DragSelfItems )
{
return wxDragNone;
}
if( !GetData() )
{
guLogMessage( wxT( "Error getting drop data" ) );
return wxDragError;
}
guDataObjectComposite * DataObject = ( guDataObjectComposite * ) m_dataObject;
wxDataFormat ReceivedFormat = DataObject->GetReceivedFormat();
//guLogMessage( wxT( "ReceivedFormat: '%s'" ), ReceivedFormat.GetId().c_str() );
if( ReceivedFormat == wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) )
{
guTrackArray * Tracks;
if( !DataObject->GetDataHere( ReceivedFormat, &Tracks ) )
{
guLogMessage( wxT( "Error getting tracks data..." ) );
}
else
{
m_ListView->OnDropTracks( Tracks );
m_ListView->OnDropEnd();
}
}
else if( ReceivedFormat == wxDataFormat( wxDF_FILENAME ) )
{
m_DropFilesThreadMutex.Lock();
if( m_ListViewDropFilesThread )
{
m_ListViewDropFilesThread->Pause();
m_ListViewDropFilesThread->Delete();
m_ListViewDropFilesThread = NULL;
}
wxFileDataObject * FileDataObject = ( wxFileDataObject * ) DataObject->GetDataObject( wxDataFormat( wxDF_FILENAME ) );
if( FileDataObject )
{
m_ListViewDropFilesThread = new guListViewDropFilesThread( this, m_ListView, FileDataObject->GetFilenames() );
if( !m_ListViewDropFilesThread )
{
guLogError( wxT( "Could not create the add files thread." ) );
}
}
m_DropFilesThreadMutex.Unlock();
}
return def;
}
// -------------------------------------------------------------------------------- //
bool guListViewDropTarget::OnDrop( wxCoord x, wxCoord y )
{
//guLogMessage( wxT( "OnDrop %i / %i" ), m_ListView->m_DragSelfItems, m_ListView->m_DragSelfItemsEnabled );
// We are moving items inside this object.
if( m_ListView->m_DragSelfItems )
{
if( m_ListView->m_DragSelfItemsEnabled )
{
m_ListView->MoveSelection();
}
m_ListView->RefreshAll();
}
else
{
m_ListView->OnDropBegin();
}
return true;
}
// -------------------------------------------------------------------------------- //
void guListViewDropTarget::OnLeave()
{
int MouseX, MouseY;
wxGetMousePosition( &MouseX, &MouseY );
//m_ListView->ScreenToClient( &MouseX, &MouseY );
wxRect ScreenRect = m_ListView->GetClientScreenRect();
//guLogMessage( wxT( "guListViewDropTarget::OnLeave %i, %i -> ( %i, %i, %i, %i )" ), MouseX, MouseY, ScreenRect.x, ScreenRect.y, ScreenRect.x + ScreenRect.width, ScreenRect.y + ScreenRect.height );
if( !ScreenRect.Contains( MouseX, MouseY ) ) //( m_ListView->HitTest( MouseX, MouseY ) == wxNOT_FOUND ) )
{
m_ListView->m_DragOverItem = wxNOT_FOUND;
//m_ListView->m_DragSelfItems = false;
m_ListView->RefreshAll();
}
}
// -------------------------------------------------------------------------------- //
wxDragResult guListViewDropTarget::OnDragOver( wxCoord x, wxCoord y, wxDragResult def )
{
//printf( "guListViewDropTarget::OnDragOver... %d - %d\n", x, y );
m_ListView->OnDragOver( x, y );
return wxDragCopy;
}
// -------------------------------------------------------------------------------- //
// guDataObjectComposite
// -------------------------------------------------------------------------------- //
void guDataObjectComposite::SetFiles( const wxArrayString &files )
{
wxFileDataObject * FileDataObject = new wxFileDataObject();
int Count = files.Count();
for( int Index = 0; Index < Count; Index++ )
{
FileDataObject->AddFile( files[ Index ] );
}
Add( FileDataObject );
}
// -------------------------------------------------------------------------------- //
void guDataObjectComposite::SetTracks( const guTrackArray &tracks )
{
wxCustomDataObject * TracksObject = new wxCustomDataObject( wxDataFormat( wxT( "x-gutracks/guayadeque-copied-tracks" ) ) );
m_Tracks = new guTrackArray();
int Count = tracks.Count();
for( int Index = 0; Index < Count; Index++ )
{
m_Tracks->Add( new guTrack( tracks[ Index ] ) );
}
TracksObject->SetData( sizeof( m_Tracks ), &m_Tracks );
Add( TracksObject );
}
}
// -------------------------------------------------------------------------------- //
| 60,572
|
C++
|
.cpp
| 1,670
| 29.465868
| 221
| 0.51058
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
750,637
|
Shoutcast.cpp
|
anonbeat_guayadeque/src/ui/radios/Shoutcast.cpp
|
// -------------------------------------------------------------------------------- //
// Copyright (C) 2008-2023 J.Rios anonbeat@gmail.com
//
// This Program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, 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 the file LICENSE. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/copyleft/gpl.html
//
// -------------------------------------------------------------------------------- //
//
// Here is the complete API for newxml.phtml, for non-commerical purposes.
//
// Top Level Genre Listing
// http://yp.shoutcast.com/sbin/newxml.phtml
//
// returns list of genres
// <genrelist>
// <genre name="Rock"></genre>
// </genrelist>
//
// Station List on Genre
// http://yp.shoutcast.com/sbin/newxml.phtml?genre=Trance
//
// <stationlist>
// <tunein base="/sbin/tunein-station.pls"></tunein>
// <station name=" -=Sputnik Radio Muzika=- Hi Def Sound..WARNING: Subliminal Suggestions in audio.... Server FULL? Do" mt="audio/aacp" id="639026" br="128" genre="Trance Dance Pop" ct="Gabriel & Dresden - Sydney (Organised nature)" lc="45"></station>
// </stationlist>
//
// name = station name
// mt = MIME type, determines the codec used. audio/mpeg for MP3 and audio/aacp for aacPlus
// id = station ID. use this when connecting to http://yp.shoutcast.com/tunein-station.pls?id=12345 to retrieve the playlist containing the station URL
// br = station bitrate
// genre = station genre. This is a "freeform" text. These are used to populate the genre list. Calling the API with ?genre=xyz essential does a like genre like %xyz% database query.
// ct = currently playing track. not gauranteed to be up-to-date because of database caching
// lc = listener count
//
//
// Station List on Search
// http://yp.shoutcast.com/sbin/newxml.phtml?search=[UrlEncodedSearchString]
//
// same results as the genre listings, but search searches station name, current playing track and genre
//
// To limit results
// add &limit=%d to limit xml entry results where %d is the number of items to return
//
// Top 500:
// Request genre=Top500
//
//
//
// 20 Random Stations
//
// Request genre=random
//
//
// RSS 2.0 version
//
// append &rss=1 to the url
//
// *** ALL STATION LISTS EXCEPT RANDOM, ARE SORTED BY LISTENER COUNT ***
//
//
// To tune into a station, find the id="" attribute in the xml and call
// http://yp.shoutcast.com/sbin/tunein-station.pls?id=1025
//
#include "Shoutcast.h"
#include "Utils.h"
#include "PlayListFile.h"
#include <wx/xml/xml.h>
#include <wx/fileconf.h>
#include <wx/sstream.h>
namespace Guayadeque {
//#define SHOUTCAST_GET_GENRE_URL wxT( "http://yp.shoutcast.com/sbin/newxml.phtml" )
//s o 1 N 1 5 v h C B 7 8 Z 6 k 4 __ s h 1 i q r P H n h j F m X i T __ f a 1 _ B m i c Y Q P D b b K m
//a m 1 S G I 9 p 6 W l 8 Y b b W __ f a 1 6 6 9 M u i R P o r U B w __ s h 1 7 t O U i _ e z L 6 1 _ A
//s h 1 t 7 h y n 3 K h 0 j h l V __ l a 1 C s E T N q U a q y u e d
#define SHOUTCAST_DEV_KEY0 "sh1iqrPH"
#define SHOUTCAST_DEV_KEY1 "nhjFmXiT"
#define SHOUTCAST_DEV_KEY SHOUTCAST_DEV_KEY0 SHOUTCAST_DEV_KEY1
#define SHOUTCAST_GET_GENRE_URL wxT( "http://api.shoutcast.com/legacy/genrelist?k=" SHOUTCAST_DEV_KEY )
//#define SHOUTCAST_GET_STATIONS_URL wxT( "http://yp.shoutcast.com/sbin/newxml.phtml?genre=%s" )
#define SHOUTCAST_GET_STATIONS_URL wxT( "http://api.shoutcast.com/legacy/genresearch?k=" SHOUTCAST_DEV_KEY "&genre=%s" )
//#define SHOUTCAST_SEARCH_STATIONS_URL wxT( "http://yp.shoutcast.com/sbin/newxml.phtml?search=%s" )
#define SHOUTCAST_SEARCH_STATIONS_URL wxT( "http://api.shoutcast.com/legacy/stationsearch?k=" SHOUTCAST_DEV_KEY "&search=%s" )
//#define SHOUTCAST_GET_STATION_PLAYLIST wxT( "http://yp.shoutcast.com/sbin/tunein-station.pls?id=%u" )
#define SHOUTCAST_GET_STATION_PLAYLIST wxT( "http://yp.shoutcast.com/sbin/tunein-station.pls?id=%u" )
// -------------------------------------------------------------------------------- //
wxArrayString guShoutCast::GetGenres( void ) const
{
wxArrayString RetVal;
wxString Content;
wxString GenreName;
Content = GetUrlContent( SHOUTCAST_GET_GENRE_URL );
if( Content.Length() )
{
wxStringInputStream InStr( Content );
wxXmlDocument XmlDoc( InStr );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "genrelist" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "genre" ) )
{
XmlNode->GetAttribute( wxT( "name" ), &GenreName );
RetVal.Add( GenreName );
//guLogMessage( wxT( "Genre : %s" ), GenreName.c_str() );
}
XmlNode = XmlNode->GetNext();
}
}
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
void guShoutCast::GetStations( const int source, const int flags, const wxString &GenreName, const int GenreId, guRadioStations * Stations, long MinBitRate ) const
{
wxString Content;
wxString Value;
long BitRate;
wxString StationName;
wxString StationType;
wxString StationGenre;
wxString StationCurrent;
long StationId;
long Listeners;
//guLogMessage( wxT( "About to get stations for genre '%s'" ), GenreName.c_str() );
//
//guLogMessage( wxT( "GetStations:\n%s" ), wxString::Format( source == guRADIO_SOURCE_SHOUTCAST_GENRE ?
// SHOUTCAST_GET_STATIONS_URL : SHOUTCAST_SEARCH_STATIONS_URL, guURLEncode( GenreName ).c_str() ).c_str() );
Content = GetUrlContent( wxString::Format( source == guRADIO_SOURCE_SHOUTCAST_GENRE ?
SHOUTCAST_GET_STATIONS_URL : SHOUTCAST_SEARCH_STATIONS_URL, guURLEncode( GenreName ).c_str() ),
wxEmptyString, true );
//
if( Content.Length() )
{
wxStringInputStream InStr( Content );
wxXmlDocument XmlDoc( InStr );
wxXmlNode * XmlNode = XmlDoc.GetRoot();
if( XmlNode && XmlNode->GetName() == wxT( "stationlist" ) )
{
XmlNode = XmlNode->GetChildren();
while( XmlNode )
{
if( XmlNode->GetName() == wxT( "station" ) )
{
XmlNode->GetAttribute( wxT( "br" ), &Value );
Value.ToLong( &BitRate );
if( ( MinBitRate == SHOUTCAST_STATION_ALLBITRATES ) ||
( MinBitRate <= BitRate ) )
{
XmlNode->GetAttribute( wxT( "name" ), &StationName );
StationName.Replace( wxT( " - [SHOUTcast.com]" ), wxT( "" ) );
StationName.Replace( wxT( " - a SHOUTcast.com member station" ), wxT( "" ) );
XmlNode->GetAttribute( wxT( "mt" ), &StationType );
XmlNode->GetAttribute( wxT( "genre" ), &StationGenre );
XmlNode->GetAttribute( wxT( "ct" ), &StationCurrent );
XmlNode->GetAttribute( wxT( "id" ), &Value );
Value.ToLong( &StationId );
XmlNode->GetAttribute( wxT( "lc" ), &Value );
Value.ToLong( &Listeners );
if( StationType.StartsWith( wxT( "audio" ) ) )
{
guRadioStation * RadioStation = new guRadioStation();
if( RadioStation )
{
RadioStation->m_Id = wxNOT_FOUND;
RadioStation->m_Name = StationName;
RadioStation->m_SCId = StationId;
RadioStation->m_Type = StationType;
RadioStation->m_GenreId = GenreId;
RadioStation->m_GenreName = StationGenre;
RadioStation->m_Source = source;
RadioStation->m_Listeners = Listeners;
RadioStation->m_BitRate = BitRate;
RadioStation->m_NowPlaying = StationCurrent;
Stations->Add( RadioStation );
//guLogMessage( wxT( "Station: '%s'" ), RadioStation->m_Name.c_str() );
}
}
}
}
XmlNode = XmlNode->GetNext();
}
}
}
else
{
guLogError( wxT( "ee: Could not get radio stations for genre '%s'" ), GenreName.c_str() );
}
}
// -------------------------------------------------------------------------------- //
wxString guShoutCast::GetStationUrl( const int id ) const
{
return wxString::Format( SHOUTCAST_GET_STATION_PLAYLIST, id );
}
// -------------------------------------------------------------------------------- //
guPlaylistItemArray guShoutCast::GetStationPlayList( const int StationId ) const
{
return GetStationPlayList( wxString::Format( SHOUTCAST_GET_STATION_PLAYLIST, StationId ) );
}
// -------------------------------------------------------------------------------- //
guPlaylistItemArray guShoutCast::GetStationPlayList( const wxString &stationurl ) const
{
wxString Content;
guPlaylistItemArray RetVal;
guPlaylistItem * NewStation;
wxFileConfig * PlayList;
Content = GetUrlContent( stationurl );
if( Content.Length() )
{
//guLogMessage( Content );
wxStringInputStream ConfigData( Content );
PlayList = new wxFileConfig( ConfigData );
if( PlayList )
{
if( PlayList->HasGroup( wxT( "playlist" ) ) )
{
PlayList->SetPath( wxT( "playlist" ) );
int count;
if( PlayList->Read( wxT( "numberofentries" ), &count ) )
{
if( !count )
{
guLogMessage( wxT( "This station playlist is empty" ) );
}
else
{
for( int index = 1; index <= count; index++ )
{
NewStation = new guPlaylistItem();
PlayList->Read( wxString::Format( wxT( "File%u" ), index ), &NewStation->m_Location );
PlayList->Read( wxString::Format( wxT( "Title%u" ), index ), &NewStation->m_Name );
if( NewStation->m_Name.IsEmpty() )
NewStation->m_Name = NewStation->m_Location;
RetVal.Add( NewStation );
}
}
}
}
else
{
guLogError( wxT( "ee: Station Playlist without 'playlist' group" ) );
}
delete PlayList;
}
else
guLogError( wxT( "ee: Station Playlist empty" ) );
}
else
{
guLogError( wxT( "Retrieving station playlist empty response" ) );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxString GetProperty( const wxString Content, const wxString Name )
{
wxString RetVal;
int StrPos = Content.Find( Name );
if( StrPos != wxNOT_FOUND )
{
RetVal = Content.Mid( StrPos );
RetVal = RetVal.Mid( RetVal.Find( wxT( "class=default><b>" ) ) );
RetVal = RetVal.Mid( 17 );
RetVal = RetVal.Mid( 0, RetVal.Find( wxT( "</b>" ) ) );
//guLogMessage( Name + RetVal );
}
return RetVal;
}
// -------------------------------------------------------------------------------- //
wxArrayString guShoutCast::GetStationStatus( const wxString ServerUrl )
{
wxString Content;
wxArrayString RetVal;
//
if( m_LastServerUrl != ServerUrl )
{
Content = ServerUrl;
if( !Content.EndsWith( wxT( "/" ) ) )
Content.Append( wxT( "/" ) );
Content = GetUrlContent( Content );
if( Content.Length() )
{
Content = Content.Mid( Content.Find( wxT( "Current Stream Information" ) ) );
RetVal.Add( GetProperty( Content, wxT( "Stream Title: " ) ) );
RetVal.Add( GetProperty( Content, wxT( "Content Type: " ) ) );
RetVal.Add( GetProperty( Content, wxT( "Current Song: " ) ) );
}
m_LastServerData = RetVal;
m_LastServerUrl = ServerUrl;
}
return m_LastServerData;
}
}
// -------------------------------------------------------------------------------- //
| 13,565
|
C++
|
.cpp
| 309
| 35.087379
| 254
| 0.533626
|
anonbeat/guayadeque
| 130
| 29
| 42
|
GPL-3.0
|
9/20/2024, 9:41:57 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.