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
29,658
PrintInstanceInfo.h
PrismLauncher_PrismLauncher/launcher/minecraft/launch/PrintInstanceInfo.h
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <launch/LaunchStep.h> #include "minecraft/auth/AuthSession.h" #include "minecraft/launch/MinecraftTarget.h" // FIXME: temporary wrapper for existing task. class PrintInstanceInfo : public LaunchStep { Q_OBJECT public: explicit PrintInstanceInfo(LaunchTask* parent, AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) : LaunchStep(parent), m_session(session), m_targetToJoin(targetToJoin) {}; virtual ~PrintInstanceInfo() = default; virtual void executeTask(); virtual bool canAbort() const { return false; } private: AuthSessionPtr m_session; MinecraftTarget::Ptr m_targetToJoin; };
1,265
C++
.h
31
37.870968
109
0.764036
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,659
LauncherPartLaunch.h
PrismLauncher_PrismLauncher/launcher/minecraft/launch/LauncherPartLaunch.h
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <LoggedProcess.h> #include <launch/LaunchStep.h> #include <minecraft/auth/AuthSession.h> #include "MinecraftTarget.h" class LauncherPartLaunch : public LaunchStep { Q_OBJECT public: explicit LauncherPartLaunch(LaunchTask* parent); virtual ~LauncherPartLaunch() = default; virtual void executeTask(); virtual bool abort(); virtual void proceed(); virtual bool canAbort() const { return true; } void setWorkingDirectory(const QString& wd); void setAuthSession(AuthSessionPtr session) { m_session = session; } void setTargetToJoin(MinecraftTarget::Ptr targetToJoin) { m_targetToJoin = std::move(targetToJoin); } private slots: void on_state(LoggedProcess::State state); private: LoggedProcess m_process; QString m_command; AuthSessionPtr m_session; QString m_launchScript; MinecraftTarget::Ptr m_targetToJoin; bool mayProceed = false; };
1,549
C++
.h
41
34.365854
105
0.754503
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,660
MinecraftTarget.h
PrismLauncher_PrismLauncher/launcher/minecraft/launch/MinecraftTarget.h
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <QString> struct MinecraftTarget { QString address; quint16 port; QString world; static MinecraftTarget parse(const QString& fullAddress, bool useWorld); using Ptr = std::shared_ptr<MinecraftTarget>; };
874
C++
.h
24
33.833333
76
0.760947
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,661
AutoInstallJava.h
PrismLauncher_PrismLauncher/launcher/minecraft/launch/AutoInstallJava.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <launch/LaunchStep.h> #include <launch/LaunchTask.h> #include "meta/Version.h" #include "minecraft/MinecraftInstance.h" #include "tasks/Task.h" class AutoInstallJava : public LaunchStep { Q_OBJECT public: explicit AutoInstallJava(LaunchTask* parent); ~AutoInstallJava() override = default; void executeTask() override; bool canAbort() const override { return m_current_task ? m_current_task->canAbort() : false; } bool abort() override; protected: void setJavaPath(QString path); void setJavaPathFromPartial(); void downloadJava(Meta::Version::Ptr version, QString javaName); void tryNextMajorJava(); private: MinecraftInstancePtr m_instance; Task::Ptr m_current_task; qsizetype m_majorJavaVersionIndex = 0; const QString m_supported_arch; };
2,338
C++
.h
59
36.847458
98
0.737561
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,662
Sink.h
PrismLauncher_PrismLauncher/launcher/net/Sink.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Validator.h" #include "tasks/Task.h" namespace Net { class Sink { public: Sink() = default; virtual ~Sink() = default; public: virtual auto init(QNetworkRequest& request) -> Task::State = 0; virtual auto write(QByteArray& data) -> Task::State = 0; virtual auto abort() -> Task::State = 0; virtual auto finalize(QNetworkReply& reply) -> Task::State = 0; virtual auto hasLocalData() -> bool = 0; void addValidator(Validator* validator) { if (validator) { validators.push_back(std::shared_ptr<Validator>(validator)); } } protected: bool initAllValidators(QNetworkRequest& request) { for (auto& validator : validators) { if (!validator->init(request)) return false; } return true; } bool finalizeAllValidators(QNetworkReply& reply) { for (auto& validator : validators) { if (!validator->validate(reply)) return false; } return true; } bool failAllValidators() { bool success = true; for (auto& validator : validators) { success &= validator->abort(); } return success; } bool writeAllValidators(QByteArray& data) { for (auto& validator : validators) { if (!validator->write(data)) return false; } return true; } protected: std::vector<std::shared_ptr<Validator>> validators; }; } // namespace Net
3,043
C++
.h
91
28.351648
80
0.660666
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,663
RawHeaderProxy.h
PrismLauncher_PrismLauncher/launcher/net/RawHeaderProxy.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "net/HeaderProxy.h" namespace Net { class RawHeaderProxy : public HeaderProxy { public: RawHeaderProxy(QList<HeaderPair> headers = {}) : HeaderProxy(), m_headers(std::move(headers)) {}; virtual ~RawHeaderProxy() = default; public: virtual QList<HeaderPair> headers(const QNetworkRequest&) const override { return m_headers; }; void addHeader(const HeaderPair& header) { m_headers.append(header); } void addHeader(const QByteArray& headerName, const QByteArray& headerValue) { m_headers.append({ headerName, headerValue }); } void addHeaders(const QList<HeaderPair>& headers) { m_headers.append(headers); } void setHeaders(QList<HeaderPair> headers) { m_headers = headers; }; private: QList<HeaderPair> m_headers; }; } // namespace Net
1,744
C++
.h
38
43.105263
130
0.740872
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,664
NetUtils.h
PrismLauncher_PrismLauncher/launcher/net/NetUtils.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <QNetworkReply> #include <QSet> namespace Net { inline bool isApplicationError(QNetworkReply::NetworkError x) { // Mainly taken from https://github.com/qt/qtbase/blob/dev/src/network/access/qhttpthreaddelegate.cpp static QSet<QNetworkReply::NetworkError> errors = { QNetworkReply::ProtocolInvalidOperationError, QNetworkReply::AuthenticationRequiredError, QNetworkReply::ContentAccessDenied, QNetworkReply::ContentNotFoundError, QNetworkReply::ContentOperationNotPermittedError, QNetworkReply::ProxyAuthenticationRequiredError, QNetworkReply::ContentConflictError, QNetworkReply::ContentGoneError, QNetworkReply::InternalServerError, QNetworkReply::OperationNotImplementedError, QNetworkReply::ServiceUnavailableError, QNetworkReply::UnknownServerError, QNetworkReply::UnknownContentError }; return errors.contains(x); } } // namespace Net
2,282
C++
.h
40
38.5
105
0.571237
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,665
ApiDownload.h
PrismLauncher_PrismLauncher/launcher/net/ApiDownload.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "Download.h" namespace Net { namespace ApiDownload { Download::Ptr makeCached(QUrl url, MetaEntryPtr entry, Download::Options options = Download::Option::NoOptions); Download::Ptr makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Download::Options options = Download::Option::NoOptions); Download::Ptr makeFile(QUrl url, QString path, Download::Options options = Download::Option::NoOptions); }; // namespace ApiDownload } // namespace Net
1,241
C++
.h
27
44.185185
131
0.763441
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,666
Validator.h
PrismLauncher_PrismLauncher/launcher/net/Validator.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QNetworkReply> namespace Net { class Validator { public: /* con/des */ Validator() {} virtual ~Validator() {} public: /* methods */ virtual bool init(QNetworkRequest& request) = 0; virtual bool write(QByteArray& data) = 0; virtual bool abort() = 0; virtual bool validate(QNetworkReply& reply) = 0; }; } // namespace Net
1,811
C++
.h
47
36.148936
80
0.719886
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,667
NetJob.h
PrismLauncher_PrismLauncher/launcher/net/NetJob.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QtNetwork> #include <QObject> #include "net/NetRequest.h" #include "tasks/ConcurrentTask.h" // Those are included so that they are also included by anyone using NetJob #include "net/Download.h" #include "net/HttpMetaCache.h" class NetJob : public ConcurrentTask { Q_OBJECT public: using Ptr = shared_qobject_ptr<NetJob>; explicit NetJob(QString job_name, shared_qobject_ptr<QNetworkAccessManager> network, int max_concurrent = -1); ~NetJob() override = default; auto size() const -> int; auto canAbort() const -> bool override; auto addNetAction(Net::NetRequest::Ptr action) -> bool; auto getFailedActions() -> QList<Net::NetRequest*>; auto getFailedFiles() -> QList<QString>; void setAskRetry(bool askRetry); public slots: // Qt can't handle auto at the start for some reason? bool abort() override; void emitFailed(QString reason) override; protected slots: void executeNextSubTask() override; protected: void updateState() override; bool isOnline(); private: shared_qobject_ptr<QNetworkAccessManager> m_network; int m_try = 1; bool m_ask_retry = true; int m_manual_try = 0; };
2,775
C++
.h
70
36.6
114
0.727881
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,668
Logging.h
PrismLauncher_PrismLauncher/launcher/net/Logging.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <QLoggingCategory> Q_DECLARE_LOGGING_CATEGORY(taskNetLogC) Q_DECLARE_LOGGING_CATEGORY(taskDownloadLogC) Q_DECLARE_LOGGING_CATEGORY(taskUploadLogC) Q_DECLARE_LOGGING_CATEGORY(taskMCSkinsLogC) Q_DECLARE_LOGGING_CATEGORY(taskMetaCacheLogC) Q_DECLARE_LOGGING_CATEGORY(taskHttpMetaCacheLogC)
1,074
C++
.h
26
39.576923
75
0.786603
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,669
ApiHeaderProxy.h
PrismLauncher_PrismLauncher/launcher/net/ApiHeaderProxy.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "Application.h" #include "BuildConfig.h" #include "net/HeaderProxy.h" namespace Net { class ApiHeaderProxy : public HeaderProxy { public: ApiHeaderProxy() : HeaderProxy() {} virtual ~ApiHeaderProxy() = default; public: virtual QList<HeaderPair> headers(const QNetworkRequest& request) const override { QList<HeaderPair> hdrs; if (APPLICATION->capabilities() & Application::SupportsFlame && request.url().host() == QUrl(BuildConfig.FLAME_BASE_URL).host()) { hdrs.append({ "x-api-key", APPLICATION->getFlameAPIKey().toUtf8() }); } else if (request.url().host() == QUrl(BuildConfig.MODRINTH_PROD_URL).host() || request.url().host() == QUrl(BuildConfig.MODRINTH_STAGING_URL).host()) { QString token = APPLICATION->getModrinthAPIToken(); if (!token.isNull()) hdrs.append({ "Authorization", token.toUtf8() }); } return hdrs; }; }; } // namespace Net
1,772
C++
.h
43
36.511628
138
0.688334
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,670
Upload.h
PrismLauncher_PrismLauncher/launcher/net/Upload.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "net/NetRequest.h" namespace Net { class Upload : public NetRequest { Q_OBJECT public: using Ptr = shared_qobject_ptr<Upload>; explicit Upload() : NetRequest() { logCat = taskUploadLogC; }; static Upload::Ptr makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data); protected: virtual QNetworkReply* getReply(QNetworkRequest&) override; QByteArray m_post_data; }; } // namespace Net
2,093
C++
.h
50
39.44
107
0.733792
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,671
ApiUpload.h
PrismLauncher_PrismLauncher/launcher/net/ApiUpload.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "Upload.h" namespace Net { namespace ApiUpload { Upload::Ptr makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data); }; } // namespace Net
958
C++
.h
25
36.48
96
0.753233
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,672
MetaCacheSink.h
PrismLauncher_PrismLauncher/launcher/net/MetaCacheSink.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "ChecksumValidator.h" #include "FileSink.h" #include "net/HttpMetaCache.h" namespace Net { class MetaCacheSink : public FileSink { public: MetaCacheSink(MetaEntryPtr entry, ChecksumValidator* md5sum, bool is_eternal = false); virtual ~MetaCacheSink() = default; auto hasLocalData() -> bool override; protected: auto initCache(QNetworkRequest& request) -> Task::State override; auto finalizeCache(QNetworkReply& reply) -> Task::State override; private: MetaEntryPtr m_entry; ChecksumValidator* m_md5Node; bool m_is_eternal; }; } // namespace Net
2,101
C++
.h
53
37.150943
90
0.736043
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,673
ChecksumValidator.h
PrismLauncher_PrismLauncher/launcher/net/ChecksumValidator.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Validator.h" #include <QCryptographicHash> #include <QFile> namespace Net { class ChecksumValidator : public Validator { public: ChecksumValidator(QCryptographicHash::Algorithm algorithm, QString expectedHex) : Net::ChecksumValidator(algorithm, QByteArray::fromHex(expectedHex.toLatin1())) {} ChecksumValidator(QCryptographicHash::Algorithm algorithm, QByteArray expected = QByteArray()) : m_checksum(algorithm), m_expected(expected) {}; virtual ~ChecksumValidator() = default; public: auto init(QNetworkRequest&) -> bool override { m_checksum.reset(); return true; } auto write(QByteArray& data) -> bool override { m_checksum.addData(data); return true; } auto abort() -> bool override { m_checksum.reset(); return true; } auto validate(QNetworkReply&) -> bool override { if (m_expected.size() && m_expected != hash()) { qWarning() << "Checksum mismatch, download is bad."; return false; } return true; } auto hash() -> QByteArray { return m_checksum.result(); } void setExpected(QByteArray expected) { m_expected = expected; } private: QCryptographicHash m_checksum; QByteArray m_expected; }; } // namespace Net
2,836
C++
.h
78
32.230769
98
0.697852
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,674
HttpMetaCache.h
PrismLauncher_PrismLauncher/launcher/net/HttpMetaCache.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QMap> #include <QString> #include <QTimer> #include <memory> class HttpMetaCache; class MetaEntry { friend class HttpMetaCache; protected: MetaEntry() = default; public: auto isStale() -> bool { return m_stale; } void setStale(bool stale) { m_stale = stale; } auto getFullPath() -> QString; auto getRemoteChangedTimestamp() -> QString { return m_remote_changed_timestamp; } void setRemoteChangedTimestamp(QString remote_changed_timestamp) { m_remote_changed_timestamp = remote_changed_timestamp; } void setLocalChangedTimestamp(qint64 timestamp) { m_local_changed_timestamp = timestamp; } auto getETag() -> QString { return m_etag; } void setETag(QString etag) { m_etag = etag; } auto getMD5Sum() -> QString { return m_md5sum; } void setMD5Sum(QString md5sum) { m_md5sum = md5sum; } /* Whether the entry expires after some time (false) or not (true). */ void makeEternal(bool eternal) { m_is_eternal = eternal; } [[nodiscard]] bool isEternal() const { return m_is_eternal; } auto getCurrentAge() -> qint64 { return m_current_age; } void setCurrentAge(qint64 age) { m_current_age = age; } auto getMaximumAge() -> qint64 { return m_max_age; } void setMaximumAge(qint64 age) { m_max_age = age; } bool isExpired(qint64 offset) { return !m_is_eternal && (m_current_age >= m_max_age - offset); } protected: QString m_baseId; QString m_basePath; QString m_relativePath; QString m_md5sum; QString m_etag; qint64 m_local_changed_timestamp = 0; QString m_remote_changed_timestamp; // QString for now, RFC 2822 encoded time qint64 m_current_age = 0; qint64 m_max_age = 0; bool m_is_eternal = false; bool m_stale = true; }; using MetaEntryPtr = std::shared_ptr<MetaEntry>; class HttpMetaCache : public QObject { Q_OBJECT public: // supply path to the cache index file HttpMetaCache(QString path = QString()); ~HttpMetaCache() override; // get the entry solely from the cache // you probably don't want this, unless you have some specific caching needs. auto getEntry(QString base, QString resource_path) -> MetaEntryPtr; // get the entry from cache and verify that it isn't stale (within reason) auto resolveEntry(QString base, QString resource_path, QString expected_etag = QString()) -> MetaEntryPtr; // add a previously resolved stale entry auto updateEntry(MetaEntryPtr stale_entry) -> bool; // evict selected entry from cache auto evictEntry(MetaEntryPtr entry) -> bool; void evictAll(); void addBase(QString base, QString base_root); // (re)start a timer that calls SaveNow later. void SaveEventually(); void Load(); auto getBasePath(QString base) -> QString; public slots: void SaveNow(); private: // create a new stale entry, given the parameters auto staleEntry(QString base, QString resource_path) -> MetaEntryPtr; struct EntryMap { QString base_path; QMap<QString, MetaEntryPtr> entry_list; }; QMap<QString, EntryMap> m_entries; QString m_index_file; QTimer saveBatchingTimer; };
4,685
C++
.h
111
38.252252
127
0.711268
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,675
Mode.h
PrismLauncher_PrismLauncher/launcher/net/Mode.h
#pragma once namespace Net { enum class Mode { Offline, Online }; }
69
C++
.h
4
16
36
0.75
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,676
NetRequest.h
PrismLauncher_PrismLauncher/launcher/net/NetRequest.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <qloggingcategory.h> #include <QNetworkReply> #include <QUrl> #include <chrono> #include "HeaderProxy.h" #include "Sink.h" #include "Validator.h" #include "QObjectPtr.h" #include "net/Logging.h" #include "tasks/Task.h" namespace Net { class NetRequest : public Task { Q_OBJECT protected: explicit NetRequest() : Task() {} public: using Ptr = shared_qobject_ptr<class NetRequest>; enum class Option { NoOptions = 0, AcceptLocalFiles = 1, MakeEternal = 2 }; Q_DECLARE_FLAGS(Options, Option) public: ~NetRequest() override = default; void addValidator(Validator* v); auto abort() -> bool override; auto canAbort() const -> bool override { return true; } void setNetwork(shared_qobject_ptr<QNetworkAccessManager> network) { m_network = network; } void addHeaderProxy(Net::HeaderProxy* proxy) { m_headerProxies.push_back(std::shared_ptr<Net::HeaderProxy>(proxy)); } QUrl url() const; void setUrl(QUrl url) { m_url = url; } int replyStatusCode() const; QNetworkReply::NetworkError error() const; QString errorString() const; private: auto handleRedirect() -> bool; virtual QNetworkReply* getReply(QNetworkRequest&) = 0; protected slots: void onProgress(qint64 bytesReceived, qint64 bytesTotal); void downloadError(QNetworkReply::NetworkError error); void sslErrors(const QList<QSslError>& errors); void downloadFinished(); void downloadReadyRead(); void executeTask() override; protected: std::unique_ptr<Sink> m_sink; Options m_options; using logCatFunc = const QLoggingCategory& (*)(); logCatFunc logCat = taskUploadLogC; std::chrono::steady_clock m_clock; std::chrono::time_point<std::chrono::steady_clock> m_last_progress_time; qint64 m_last_progress_bytes; shared_qobject_ptr<QNetworkAccessManager> m_network; /// the network reply unique_qobject_ptr<QNetworkReply> m_reply; /// source URL QUrl m_url; std::vector<std::shared_ptr<Net::HeaderProxy>> m_headerProxies; }; } // namespace Net Q_DECLARE_OPERATORS_FOR_FLAGS(Net::NetRequest::Options)
3,835
C++
.h
96
36.65625
121
0.727151
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,677
ByteArraySink.h
PrismLauncher_PrismLauncher/launcher/net/ByteArraySink.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Sink.h" namespace Net { /* * Sink object for downloads that uses an external QByteArray it doesn't own as a target. */ class ByteArraySink : public Sink { public: ByteArraySink(std::shared_ptr<QByteArray> output) : m_output(output) {}; virtual ~ByteArraySink() = default; public: auto init(QNetworkRequest& request) -> Task::State override { if (m_output) m_output->clear(); else qWarning() << "ByteArraySink did not initialize the buffer because it's not addressable"; if (initAllValidators(request)) return Task::State::Running; return Task::State::Failed; }; auto write(QByteArray& data) -> Task::State override { if (m_output) m_output->append(data); else qWarning() << "ByteArraySink did not write the buffer because it's not addressable"; if (writeAllValidators(data)) return Task::State::Running; return Task::State::Failed; } auto abort() -> Task::State override { failAllValidators(); return Task::State::Failed; } auto finalize(QNetworkReply& reply) -> Task::State override { if (finalizeAllValidators(reply)) return Task::State::Succeeded; return Task::State::Failed; } auto hasLocalData() -> bool override { return false; } private: std::shared_ptr<QByteArray> m_output; }; } // namespace Net
3,043
C++
.h
82
32.463415
101
0.684068
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,678
HeaderProxy.h
PrismLauncher_PrismLauncher/launcher/net/HeaderProxy.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <QDebug> #include <QNetworkRequest> namespace Net { struct HeaderPair { QByteArray headerName; QByteArray headerValue; }; class HeaderProxy { public: HeaderProxy() {} virtual ~HeaderProxy() {} public: virtual QList<HeaderPair> headers(const QNetworkRequest& request) const = 0; public: void writeHeaders(QNetworkRequest& request) { for (auto header : headers(request)) { request.setRawHeader(header.headerName, header.headerValue); } } }; } // namespace Net
1,320
C++
.h
41
28.926829
80
0.727773
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,679
PasteUpload.h
PrismLauncher_PrismLauncher/launcher/net/PasteUpload.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Lenny McLennington <lenny@sneed.church> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QBuffer> #include <QNetworkReply> #include <QString> #include <array> #include <memory> #include "tasks/Task.h" class PasteUpload : public Task { Q_OBJECT public: enum PasteType : int { // 0x0.st NullPointer, // hastebin.com Hastebin, // paste.gg PasteGG, // mclo.gs Mclogs, // Helpful to get the range of valid values on the enum for input sanitisation: First = NullPointer, Last = Mclogs }; struct PasteTypeInfo { const QString name; const QString defaultBase; const QString endpointPath; }; static std::array<PasteTypeInfo, 4> PasteTypes; PasteUpload(QWidget* window, QString text, QString url, PasteType pasteType); virtual ~PasteUpload(); QString pasteLink() { return m_pasteLink; } protected: virtual void executeTask(); private: QWidget* m_window; QString m_pasteLink; QString m_baseUrl; QString m_uploadUrl; PasteType m_pasteType; QByteArray m_text; std::shared_ptr<QNetworkReply> m_reply; public slots: void downloadError(QNetworkReply::NetworkError); void downloadFinished(); };
2,717
C++
.h
80
29.95
87
0.703196
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,680
Download.h
PrismLauncher_PrismLauncher/launcher/net/Download.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "HttpMetaCache.h" #include "QObjectPtr.h" #include "net/NetRequest.h" namespace Net { class Download : public NetRequest { Q_OBJECT public: using Ptr = shared_qobject_ptr<class Download>; explicit Download() : NetRequest() { logCat = taskDownloadLogC; } #if defined(LAUNCHER_APPLICATION) static auto makeCached(QUrl url, MetaEntryPtr entry, Options options = Option::NoOptions) -> Download::Ptr; #endif static auto makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Options options = Option::NoOptions) -> Download::Ptr; static auto makeFile(QUrl url, QString path, Options options = Option::NoOptions) -> Download::Ptr; protected: virtual QNetworkReply* getReply(QNetworkRequest&) override; }; } // namespace Net
2,410
C++
.h
55
41.436364
130
0.739668
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,681
FileSink.h
PrismLauncher_PrismLauncher/launcher/net/FileSink.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "PSaveFile.h" #include "Sink.h" namespace Net { class FileSink : public Sink { public: FileSink(QString filename) : m_filename(filename) {}; virtual ~FileSink() = default; public: auto init(QNetworkRequest& request) -> Task::State override; auto write(QByteArray& data) -> Task::State override; auto abort() -> Task::State override; auto finalize(QNetworkReply& reply) -> Task::State override; auto hasLocalData() -> bool override; protected: virtual auto initCache(QNetworkRequest&) -> Task::State; virtual auto finalizeCache(QNetworkReply& reply) -> Task::State; protected: QString m_filename; bool wroteAnyData = false; std::unique_ptr<PSaveFile> m_output_file; }; } // namespace Net
2,263
C++
.h
57
36.964912
80
0.72442
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,682
MurmurHash2.h
PrismLauncher_PrismLauncher/libraries/murmur2/src/MurmurHash2.h
//----------------------------------------------------------------------------- // The original MurmurHash2 was written by Austin Appleby, and is placed in the // public domain. The author hereby disclaims copyright to this source code. // // This was modified as to possibilitate it's usage incrementally. // Those modifications are also placed in the public domain, and the author of // such modifications hereby disclaims copyright to this source code. #pragma once #include <cstdint> #include <functional> namespace Murmur2 { #define KiB 1024 #define MiB 1024 * KiB class Reader { public: virtual ~Reader() = default; virtual int read(char* s, int n) = 0; virtual bool eof() = 0; virtual void goToBeginning() = 0; }; uint32_t hash(Reader* file_stream, std::size_t buffer_size = 4 * MiB, std::function<bool(char)> filter_out = [](char) { return false; }); struct IncrementalHashInfo { uint32_t h; uint32_t len; }; void FourBytes_MurmurHash2(const unsigned char* data, IncrementalHashInfo& prev); } // namespace Murmur2
1,058
C++
.h
27
36.888889
137
0.686217
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,683
rainbow.h
PrismLauncher_PrismLauncher/libraries/rainbow/include/rainbow.h
/* This was part of the KDE project - see KGuiAddons * Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net> * Copyright (C) 2007 Olaf Schmidt <ojschmidt@kde.org> * Copyright (C) 2007 Thomas Zander <zander@kde.org> * Copyright (C) 2007 Zack Rusin <zack@kde.org> * Copyright (C) 2015 Petr Mrazek <peterix@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #pragma once #include <QPainter> class QColor; /** * A set of methods used to work with colors. */ namespace Rainbow { /** * Calculate the luma of a color. Luma is weighted sum of gamma-adjusted * R'G'B' components of a color. The result is similar to qGray. The range * is from 0.0 (black) to 1.0 (white). * * Rainbow::darken(), Rainbow::lighten() and Rainbow::shade() * operate on the luma of a color. * * @see http://en.wikipedia.org/wiki/Luma_(video) */ qreal luma(const QColor&); /** * Calculate hue, chroma and luma of a color in one call. * @since 5.0 */ void getHcy(const QColor&, qreal* hue, qreal* chroma, qreal* luma, qreal* alpha = 0); /** * Calculate the contrast ratio between two colors, according to the * W3C/WCAG2.0 algorithm, (Lmax + 0.05)/(Lmin + 0.05), where Lmax and Lmin * are the luma values of the lighter color and the darker color, * respectively. * * A contrast ration of 5:1 (result == 5.0) is the minimum for "normal" * text to be considered readable (large text can go as low as 3:1). The * ratio ranges from 1:1 (result == 1.0) to 21:1 (result == 21.0). * * @see Rainbow::luma */ qreal contrastRatio(const QColor&, const QColor&); /** * Adjust the luma of a color by changing its distance from white. * * @li amount == 1.0 gives white * @li amount == 0.5 results in a color whose luma is halfway between 1.0 * and that of the original color * @li amount == 0.0 gives the original color * @li amount == -1.0 gives a color that is 'twice as far from white' as * the original color, that is luma(result) == 1.0 - 2*(1.0 - luma(color)) * * @param amount factor by which to adjust the luma component of the color * @param chromaInverseGain (optional) factor by which to adjust the chroma * component of the color; 1.0 means no change, 0.0 maximizes chroma * @see Rainbow::shade */ QColor lighten(const QColor&, qreal amount = 0.5, qreal chromaInverseGain = 1.0); /** * Adjust the luma of a color by changing its distance from black. * * @li amount == 1.0 gives black * @li amount == 0.5 results in a color whose luma is halfway between 0.0 * and that of the original color * @li amount == 0.0 gives the original color * @li amount == -1.0 gives a color that is 'twice as far from black' as * the original color, that is luma(result) == 2*luma(color) * * @param amount factor by which to adjust the luma component of the color * @param chromaGain (optional) factor by which to adjust the chroma * component of the color; 1.0 means no change, 0.0 minimizes chroma * @see Rainbow::shade */ QColor darken(const QColor&, qreal amount = 0.5, qreal chromaGain = 1.0); /** * Adjust the luma and chroma components of a color. The amount is added * to the corresponding component. * * @param lumaAmount amount by which to adjust the luma component of the * color; 0.0 results in no change, -1.0 turns anything black, 1.0 turns * anything white * @param chromaAmount (optional) amount by which to adjust the chroma * component of the color; 0.0 results in no change, -1.0 minimizes chroma, * 1.0 maximizes chroma * @see Rainbow::luma */ QColor shade(const QColor&, qreal lumaAmount, qreal chromaAmount = 0.0); /** * Create a new color by tinting one color with another. This function is * meant for creating additional colors withings the same class (background, * foreground) from colors in a different class. Therefore when @p amount * is low, the luma of @p base is mostly preserved, while the hue and * chroma of @p color is mostly inherited. * * @param base color to be tinted * @param color color with which to tint * @param amount how strongly to tint the base; 0.0 gives @p base, * 1.0 gives @p color */ QColor tint(const QColor& base, const QColor& color, qreal amount = 0.3); /** * Blend two colors into a new color by linear combination. * @code QColor lighter = Rainbow::mix(myColor, Qt::white) * @endcode * @param c1 first color. * @param c2 second color. * @param bias weight to be used for the mix. @p bias <= 0 gives @p c1, * @p bias >= 1 gives @p c2. @p bias == 0.5 gives a 50% blend of @p c1 * and @p c2. */ QColor mix(const QColor& c1, const QColor& c2, qreal bias = 0.5); /** * Blend two colors into a new color by painting the second color over the * first using the specified composition mode. * @code QColor white(Qt::white); white.setAlphaF(0.5); QColor lighter = Rainbow::overlayColors(myColor, white); @endcode * @param base the base color (alpha channel is ignored). * @param paint the color to be overlayed onto the base color. * @param comp the CompositionMode used to do the blending. */ QColor overlayColors(const QColor& base, const QColor& paint, QPainter::CompositionMode comp = QPainter::CompositionMode_SourceOver); } // namespace Rainbow
5,926
C++
.h
142
39.732394
133
0.7251
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,684
sys.h
PrismLauncher_PrismLauncher/libraries/systeminfo/include/sys.h
#pragma once #include <QString> namespace Sys { const uint64_t mebibyte = 1024ull * 1024ull; enum class KernelType { Undetermined, Windows, Darwin, Linux }; struct KernelInfo { QString kernelName; QString kernelVersion; KernelType kernelType = KernelType::Undetermined; int kernelMajor = 0; int kernelMinor = 0; int kernelPatch = 0; bool isCursed = false; }; KernelInfo getKernelInfo(); struct DistributionInfo { DistributionInfo operator+(const DistributionInfo& rhs) const { DistributionInfo out; if (!distributionName.isEmpty()) { out.distributionName = distributionName; } else { out.distributionName = rhs.distributionName; } if (!distributionVersion.isEmpty()) { out.distributionVersion = distributionVersion; } else { out.distributionVersion = rhs.distributionVersion; } return out; } QString distributionName; QString distributionVersion; }; DistributionInfo getDistributionInfo(); uint64_t getSystemRam(); } // namespace Sys
1,103
C++
.h
37
24.27027
65
0.695652
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,685
distroutils.h
PrismLauncher_PrismLauncher/libraries/systeminfo/include/distroutils.h
#include <QString> #include "sys.h" namespace Sys { struct LsbInfo { QString distributor; QString version; QString description; QString codename; }; bool main_lsb_info(LsbInfo& out); bool fallback_lsb_info(Sys::LsbInfo& out); void lsb_postprocess(Sys::LsbInfo& lsb, Sys::DistributionInfo& out); Sys::DistributionInfo read_lsb_release(); QString _extract_distribution(const QString& x); QString _extract_version(const QString& x); Sys::DistributionInfo read_legacy_release(); Sys::DistributionInfo read_os_release(); } // namespace Sys
556
C++
.h
18
28.777778
68
0.769663
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,686
qdcss.h
PrismLauncher_PrismLauncher/libraries/qdcss/include/qdcss.h
// SPDX-FileCopyrightText: 2023 kumquat-ir 66188216+kumquat-ir@users.noreply.github.com // // SPDX-License-Identifier: LGPL-3.0-only #ifndef QDCSS_H #define QDCSS_H #include <QMap> #include <QString> #include <QStringList> #include <optional> class QDCSS { // these are all we need to parse a couple string values out of a css string // lots more in the original code, yet to be ported // https://github.com/unascribed/NilLoader/blob/trunk/src/main/java/nilloader/api/lib/qdcss/QDCSS.java public: QDCSS(QString); std::optional<QString>* get(QString); private: QMap<QString, QStringList> m_data; }; #endif // QDCSS_H
652
C++
.h
20
29.85
106
0.740032
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,687
gamemode_client.h
PrismLauncher_PrismLauncher/libraries/gamemode/include/gamemode_client.h
/* Copyright (c) 2017-2019, Feral Interactive All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Feral Interactive nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CLIENT_GAMEMODE_H #define CLIENT_GAMEMODE_H /* * GameMode supports the following client functions * Requests are refcounted in the daemon * * int gamemode_request_start() - Request gamemode starts * 0 if the request was sent successfully * -1 if the request failed * * int gamemode_request_end() - Request gamemode ends * 0 if the request was sent successfully * -1 if the request failed * * GAMEMODE_AUTO can be defined to make the above two functions apply during static init and * destruction, as appropriate. In this configuration, errors will be printed to stderr * * int gamemode_query_status() - Query the current status of gamemode * 0 if gamemode is inactive * 1 if gamemode is active * 2 if gamemode is active and this client is registered * -1 if the query failed * * int gamemode_request_start_for(pid_t pid) - Request gamemode starts for another process * 0 if the request was sent successfully * -1 if the request failed * -2 if the request was rejected * * int gamemode_request_end_for(pid_t pid) - Request gamemode ends for another process * 0 if the request was sent successfully * -1 if the request failed * -2 if the request was rejected * * int gamemode_query_status_for(pid_t pid) - Query status of gamemode for another process * 0 if gamemode is inactive * 1 if gamemode is active * 2 if gamemode is active and this client is registered * -1 if the query failed * * const char* gamemode_error_string() - Get an error string * returns a string describing any of the above errors * * Note: All the above requests can be blocking - dbus requests can and will block while the daemon * handles the request. It is not recommended to make these calls in performance critical code */ #include <stdbool.h> #include <stdio.h> #include <dlfcn.h> #include <string.h> #include <sys/types.h> static char internal_gamemode_client_error_string[512] = { 0 }; /** * Load libgamemode dynamically to dislodge us from most dependencies. * This allows clients to link and/or use this regardless of runtime. * See SDL2 for an example of the reasoning behind this in terms of * dynamic versioning as well. */ static volatile int internal_libgamemode_loaded = 1; /* Typedefs for the functions to load */ typedef int (*api_call_return_int)(void); typedef const char* (*api_call_return_cstring)(void); typedef int (*api_call_pid_return_int)(pid_t); /* Storage for functors */ static api_call_return_int REAL_internal_gamemode_request_start = NULL; static api_call_return_int REAL_internal_gamemode_request_end = NULL; static api_call_return_int REAL_internal_gamemode_query_status = NULL; static api_call_return_cstring REAL_internal_gamemode_error_string = NULL; static api_call_pid_return_int REAL_internal_gamemode_request_start_for = NULL; static api_call_pid_return_int REAL_internal_gamemode_request_end_for = NULL; static api_call_pid_return_int REAL_internal_gamemode_query_status_for = NULL; /** * Internal helper to perform the symbol binding safely. * * Returns 0 on success and -1 on failure */ __attribute__((always_inline)) static inline int internal_bind_libgamemode_symbol(void* handle, const char* name, void** out_func, size_t func_size, bool required) { void* symbol_lookup = NULL; char* dl_error = NULL; /* Safely look up the symbol */ symbol_lookup = dlsym(handle, name); dl_error = dlerror(); if (required && (dl_error || !symbol_lookup)) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "dlsym failed - %s", dl_error); return -1; } /* Have the symbol correctly, copy it to make it usable */ memcpy(out_func, &symbol_lookup, func_size); return 0; } /** * Loads libgamemode and needed functions * * Returns 0 on success and -1 on failure */ __attribute__((always_inline)) static inline int internal_load_libgamemode(void) { /* We start at 1, 0 is a success and -1 is a fail */ if (internal_libgamemode_loaded != 1) { return internal_libgamemode_loaded; } /* Anonymous struct type to define our bindings */ struct binding { const char* name; void** functor; size_t func_size; bool required; } bindings[] = { { "real_gamemode_request_start", (void**)&REAL_internal_gamemode_request_start, sizeof(REAL_internal_gamemode_request_start), true }, { "real_gamemode_request_end", (void**)&REAL_internal_gamemode_request_end, sizeof(REAL_internal_gamemode_request_end), true }, { "real_gamemode_query_status", (void**)&REAL_internal_gamemode_query_status, sizeof(REAL_internal_gamemode_query_status), false }, { "real_gamemode_error_string", (void**)&REAL_internal_gamemode_error_string, sizeof(REAL_internal_gamemode_error_string), true }, { "real_gamemode_request_start_for", (void**)&REAL_internal_gamemode_request_start_for, sizeof(REAL_internal_gamemode_request_start_for), false }, { "real_gamemode_request_end_for", (void**)&REAL_internal_gamemode_request_end_for, sizeof(REAL_internal_gamemode_request_end_for), false }, { "real_gamemode_query_status_for", (void**)&REAL_internal_gamemode_query_status_for, sizeof(REAL_internal_gamemode_query_status_for), false }, }; void* libgamemode = NULL; /* Try and load libgamemode */ libgamemode = dlopen("libgamemode.so.0", RTLD_NOW); if (!libgamemode) { /* Attempt to load unversioned library for compatibility with older * versions (as of writing, there are no ABI changes between the two - * this may need to change if ever ABI-breaking changes are made) */ libgamemode = dlopen("libgamemode.so", RTLD_NOW); if (!libgamemode) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "dlopen failed - %s", dlerror()); internal_libgamemode_loaded = -1; return -1; } } /* Attempt to bind all symbols */ for (size_t i = 0; i < sizeof(bindings) / sizeof(bindings[0]); i++) { struct binding* binder = &bindings[i]; if (internal_bind_libgamemode_symbol(libgamemode, binder->name, binder->functor, binder->func_size, binder->required)) { internal_libgamemode_loaded = -1; return -1; }; } /* Success */ internal_libgamemode_loaded = 0; return 0; } /** * Redirect to the real libgamemode */ __attribute__((always_inline)) static inline const char* gamemode_error_string(void) { /* If we fail to load the system gamemode, or we have an error string already, return our error * string instead of diverting to the system version */ if (internal_load_libgamemode() < 0 || internal_gamemode_client_error_string[0] != '\0') { return internal_gamemode_client_error_string; } return REAL_internal_gamemode_error_string(); } /** * Redirect to the real libgamemode * Allow automatically requesting game mode * Also prints errors as they happen. */ #ifdef GAMEMODE_AUTO __attribute__((constructor)) #else __attribute__((always_inline)) static inline #endif int gamemode_request_start(void) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { #ifdef GAMEMODE_AUTO fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif return -1; } if (REAL_internal_gamemode_request_start() < 0) { #ifdef GAMEMODE_AUTO fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif return -1; } return 0; } /* Redirect to the real libgamemode */ #ifdef GAMEMODE_AUTO __attribute__((destructor)) #else __attribute__((always_inline)) static inline #endif int gamemode_request_end(void) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { #ifdef GAMEMODE_AUTO fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif return -1; } if (REAL_internal_gamemode_request_end() < 0) { #ifdef GAMEMODE_AUTO fprintf(stderr, "gamemodeauto: %s\n", gamemode_error_string()); #endif return -1; } return 0; } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_query_status(void) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { return -1; } if (REAL_internal_gamemode_query_status == NULL) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "gamemode_query_status missing (older host?)"); return -1; } return REAL_internal_gamemode_query_status(); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_request_start_for(pid_t pid) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { return -1; } if (REAL_internal_gamemode_request_start_for == NULL) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "gamemode_request_start_for missing (older host?)"); return -1; } return REAL_internal_gamemode_request_start_for(pid); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_request_end_for(pid_t pid) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { return -1; } if (REAL_internal_gamemode_request_end_for == NULL) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "gamemode_request_end_for missing (older host?)"); return -1; } return REAL_internal_gamemode_request_end_for(pid); } /* Redirect to the real libgamemode */ __attribute__((always_inline)) static inline int gamemode_query_status_for(pid_t pid) { /* Need to load gamemode */ if (internal_load_libgamemode() < 0) { return -1; } if (REAL_internal_gamemode_query_status_for == NULL) { snprintf(internal_gamemode_client_error_string, sizeof(internal_gamemode_client_error_string), "gamemode_query_status_for missing (older host?)"); return -1; } return REAL_internal_gamemode_query_status_for(pid); } #endif // CLIENT_GAMEMODE_H
12,270
C++
.h
294
36.482993
140
0.690606
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,688
LocalPeer.h
PrismLauncher_PrismLauncher/libraries/LocalPeer/include/LocalPeer.h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #pragma once #include <QObject> #include <QString> #include <memory> class QLocalServer; class LockedFile; class ApplicationId { public: /* methods */ // traditional app = installed system wide and used in a multi-user environment static ApplicationId fromTraditionalApp(); // ID based on a path with all the application data (no two instances with the same data path should run) static ApplicationId fromPathAndVersion(const QString& dataPath, const QString& version); // custom ID static ApplicationId fromCustomId(const QString& id); // custom ID, based on a raw string previously acquired from 'toString' static ApplicationId fromRawString(const QString& id); QString toString() { return m_id; } private: /* methods */ ApplicationId(const QString& value) { m_id = value; } private: /* data */ QString m_id; }; class LocalPeer : public QObject { Q_OBJECT public: LocalPeer(QObject* parent, const ApplicationId& appId); ~LocalPeer(); bool isClient(); bool sendMessage(const QByteArray& message, int timeout); ApplicationId applicationId() const; Q_SIGNALS: void messageReceived(const QByteArray& message); protected Q_SLOTS: void receiveConnection(); protected: ApplicationId id; QString socketName; std::unique_ptr<QLocalServer> server; std::unique_ptr<LockedFile> lockFile; };
3,395
C++
.h
79
40.405063
109
0.714977
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,690
BuildConfig.h
PrismLauncher_PrismLauncher/buildconfig/BuildConfig.h
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QList> #include <QString> /** * \brief The Config class holds all the build-time information passed from the build system. */ class Config { public: Config(); QString LAUNCHER_NAME; QString LAUNCHER_APP_BINARY_NAME; QString LAUNCHER_DISPLAYNAME; QString LAUNCHER_COPYRIGHT; QString LAUNCHER_DOMAIN; QString LAUNCHER_CONFIGFILE; QString LAUNCHER_GIT; QString LAUNCHER_DESKTOPFILENAME; QString LAUNCHER_SVGFILENAME; /// The major version number. int VERSION_MAJOR; /// The minor version number. int VERSION_MINOR; /** * The version channel * This is used by the updater to determine what channel the current version came from. */ QString VERSION_CHANNEL; bool UPDATER_ENABLED = false; bool JAVA_DOWNLOADER_ENABLED = false; /// A short string identifying this build's platform or distribution. QString BUILD_PLATFORM; /// A short string identifying this build's valid artifacts int he updater. For example, "lin64" or "win32". QString BUILD_ARTIFACT; /// A string containing the build timestamp QString BUILD_DATE; /// A string identifying the compiler use to build QString COMPILER_NAME; /// A string identifying the compiler version used to build QString COMPILER_VERSION; /// A string identifying the compiler target system os QString COMPILER_TARGET_SYSTEM; /// A String identifying the compiler target system version QString COMPILER_TARGET_SYSTEM_VERSION; /// A String identifying the compiler target processor QString COMPILER_TARGET_SYSTEM_PROCESSOR; /// URL for the updater's channel QString UPDATER_GITHUB_REPO; /// The public key used to sign releases for the Sparkle updater appcast QString MAC_SPARKLE_PUB_KEY; /// URL for the Sparkle updater's appcast QString MAC_SPARKLE_APPCAST_URL; /// User-Agent to use. QString USER_AGENT; /// User-Agent to use for uncached requests. QString USER_AGENT_UNCACHED; /// The git commit hash of this build QString GIT_COMMIT; /// The git tag of this build QString GIT_TAG; /// The git refspec of this build QString GIT_REFSPEC; /** * This is used to fetch the news RSS feed. * It defaults in CMakeLists.txt to "https://multimc.org/rss.xml" */ QString NEWS_RSS_URL; /** * URL that gets opened when the user clicks "More News" */ QString NEWS_OPEN_URL; /** * URL (with arg %1 to be substituted with page-id) that gets opened when the user requests help */ QString HELP_URL; /** * URL that gets opened when the user succesfully logins. */ QString LOGIN_CALLBACK_URL; /** * Client ID you can get from Imgur when you register an application */ QString IMGUR_CLIENT_ID; /** * Client ID you can get from Microsoft Identity Platform when you register an application */ QString MSA_CLIENT_ID; /** * Client API key for CurseForge */ QString FLAME_API_KEY; /** * Metadata repository URL prefix */ QString META_URL; QString GLFW_LIBRARY_NAME; QString OPENAL_LIBRARY_NAME; QString BUG_TRACKER_URL; QString TRANSLATIONS_URL; QString MATRIX_URL; QString DISCORD_URL; QString SUBREDDIT_URL; QString RESOURCE_BASE = "https://resources.download.minecraft.net/"; QString LIBRARY_BASE = "https://libraries.minecraft.net/"; QString IMGUR_BASE_URL = "https://api.imgur.com/3/"; QString FMLLIBS_BASE_URL; QString TRANSLATION_FILES_URL; QString MODPACKSCH_API_BASE_URL = "https://api.modpacks.ch/"; QString LEGACY_FTB_CDN_BASE_URL = "https://dist.creeper.host/FTB2/"; QString ATL_DOWNLOAD_SERVER_URL = "https://download.nodecdn.net/containers/atl/"; QString ATL_API_BASE_URL = "https://api.atlauncher.com/v1/"; QString TECHNIC_API_BASE_URL = "https://api.technicpack.net/"; /** * The build that is reported to the Technic API. */ QString TECHNIC_API_BUILD = "multimc"; QString MODRINTH_STAGING_URL = "https://staging-api.modrinth.com/v2"; QString MODRINTH_PROD_URL = "https://api.modrinth.com/v2"; QStringList MODRINTH_MRPACK_HOSTS{ "cdn.modrinth.com", "github.com", "raw.githubusercontent.com", "gitlab.com" }; QString FLAME_BASE_URL = "https://api.curseforge.com/v1"; QString versionString() const; /** * \brief Converts the Version to a string. * \return The version number in string format (major.minor.revision.build). */ QString printableVersionString() const; /** * \brief Compiler ID String * \return a string of the form "Name - Version" of just "Name" if the version is empty */ QString compilerID() const; /** * \brief System ID String * \return a string of the form "OS Verison Processor" */ QString systemID() const; }; extern const Config BuildConfig;
6,614
C++
.h
173
33.647399
117
0.702922
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,691
DummyResourceAPI.h
PrismLauncher_PrismLauncher/tests/DummyResourceAPI.h
#pragma once #include <QJsonDocument> #include <modplatform/ResourceAPI.h> class SearchTask : public Task { Q_OBJECT public: void executeTask() override { emitSucceeded(); } }; class DummyResourceAPI : public ResourceAPI { public: static auto searchRequestResult() { static QByteArray json_response = "{\"hits\":[" "{" "\"author\":\"flowln\"," "\"description\":\"the bestest mod\"," "\"project_id\":\"something\"," "\"project_type\":\"mod\"," "\"slug\":\"bip_bop\"," "\"title\":\"AAAAAAAA\"," "\"versions\":[\"2.71\"]" "}" "]}"; return QJsonDocument::fromJson(json_response); } DummyResourceAPI() : ResourceAPI() {} [[nodiscard]] auto getSortingMethods() const -> QList<SortingMethod> override { return {}; } [[nodiscard]] Task::Ptr searchProjects(SearchArgs&&, SearchCallbacks&& callbacks) const override { auto task = makeShared<SearchTask>(); QObject::connect(task.get(), &Task::succeeded, [callbacks] { auto json = searchRequestResult(); callbacks.on_succeed(json); }); return task; } };
1,250
C++
.h
38
25.105263
100
0.565615
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,692
oscpack_build.cpp
supercollider_supercollider/external_libraries/oscpack_build.cpp
#include <boost/predef.h> #if BOOST_ENDIAN_LITTLE_BYTE #define OSC_HOST_LITTLE_ENDIAN #elif BOOST_ENDIAN_BIG_BYTE #define OSC_HOST_BIG_ENDIAN #else #error please define endianness #endif #include "oscpack_1_1_0/osc/OscOutboundPacketStream.cpp" #include "oscpack_1_1_0/osc/OscPrintReceivedElements.cpp" #include "oscpack_1_1_0/osc/OscReceivedElements.cpp" #include "oscpack_1_1_0/osc/OscTypes.cpp"
399
C++
.cpp
12
32.083333
57
0.812987
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,709
condition_variable_timed_wait_times_out.cpp
supercollider_supercollider/external_libraries/boost_sync/test/run/condition_variable_timed_wait_times_out.cpp
// Copyright (C) 2007-8 Anthony Williams // Copyright (C) 2013 Andrey Semashev // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/thread/thread.hpp> #include <boost/thread/thread_time.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/sync/locks/unique_lock.hpp> #include <boost/sync/mutexes/mutex.hpp> #include <boost/sync/condition_variables/condition_variable.hpp> #include <boost/sync/condition_variables/condition_variable_any.hpp> #include <boost/sync/support/boost_date_time.hpp> #include <boost/core/lightweight_test.hpp> #include "utils.hpp" bool fake_predicate() { return false; } unsigned const timeout_seconds=2; unsigned const timeout_grace=1; boost::posix_time::milliseconds const timeout_resolution(100); void do_test_timed_wait_times_out() { boost::sync::condition_variable cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start = boost::get_system_time(); boost::system_time const timeout = start+delay; while(cond.timed_wait(lock,timeout)) {} boost::system_time const end = boost::get_system_time(); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_timed_wait_times_out() { timed_test(&do_test_timed_wait_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_timed_wait_with_predicate_times_out() { boost::sync::condition_variable cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start = boost::get_system_time(); boost::system_time const timeout = start+delay; bool const res=cond.timed_wait(lock,timeout,fake_predicate); boost::system_time const end=boost::get_system_time(); BOOST_TEST(!res); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_timed_wait_with_predicate_times_out() { timed_test(&do_test_timed_wait_with_predicate_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_relative_timed_wait_with_predicate_times_out() { boost::sync::condition_variable cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); bool const res=cond.timed_wait(lock,delay,fake_predicate); boost::system_time const end=boost::get_system_time(); BOOST_TEST(!res); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_relative_timed_wait_with_predicate_times_out() { timed_test(&do_test_relative_timed_wait_with_predicate_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_timed_wait_relative_times_out() { boost::sync::condition_variable cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); while(cond.timed_wait(lock,delay)) {} boost::system_time const end=boost::get_system_time(); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_timed_wait_relative_times_out() { timed_test(&do_test_timed_wait_relative_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_cv_any_timed_wait_times_out() { boost::sync::condition_variable_any cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); boost::system_time const timeout=start+delay; while(cond.timed_wait(lock,timeout)) {} boost::system_time const end=boost::get_system_time(); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_cv_any_timed_wait_times_out() { timed_test(&do_test_cv_any_timed_wait_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_cv_any_timed_wait_with_predicate_times_out() { boost::sync::condition_variable_any cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); boost::system_time const timeout=start+delay; bool const res=cond.timed_wait(lock,timeout,fake_predicate); boost::system_time const end=boost::get_system_time(); BOOST_TEST(!res); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_cv_any_timed_wait_with_predicate_times_out() { timed_test(&do_test_cv_any_timed_wait_with_predicate_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_cv_any_relative_timed_wait_with_predicate_times_out() { boost::sync::condition_variable_any cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); bool const res=cond.timed_wait(lock,delay,fake_predicate); boost::system_time const end=boost::get_system_time(); BOOST_TEST(!res); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_cv_any_relative_timed_wait_with_predicate_times_out() { timed_test(&do_test_cv_any_relative_timed_wait_with_predicate_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } void do_test_cv_any_timed_wait_relative_times_out() { boost::sync::condition_variable_any cond; boost::sync::mutex m; boost::posix_time::seconds const delay(timeout_seconds); boost::sync::unique_lock<boost::sync::mutex> lock(m); boost::system_time const start=boost::get_system_time(); while(cond.timed_wait(lock,delay)) {} boost::system_time const end=boost::get_system_time(); BOOST_TEST((delay-timeout_resolution)<=(end-start)); } void test_cv_any_timed_wait_relative_times_out() { timed_test(&do_test_cv_any_timed_wait_relative_times_out, timeout_seconds+timeout_grace, execution_monitor::use_mutex); } int main() { test_timed_wait_times_out(); test_timed_wait_with_predicate_times_out(); test_relative_timed_wait_with_predicate_times_out(); test_timed_wait_relative_times_out(); test_cv_any_timed_wait_times_out(); test_cv_any_timed_wait_with_predicate_times_out(); test_cv_any_relative_timed_wait_with_predicate_times_out(); test_cv_any_timed_wait_relative_times_out(); return boost::report_errors(); }
6,865
C++
.cpp
162
38.876543
138
0.732803
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
29,712
at_thread_exit.cpp
supercollider_supercollider/external_libraries/boost_sync/test/run/at_thread_exit.cpp
/* * Copyright Andrey Semashev 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file at_thread_exit.cpp * * \brief This test checks that \c at_thread_exit works */ #include <boost/core/lightweight_test.hpp> #include <boost/thread/thread.hpp> #include <boost/sync/thread_specific/at_thread_exit.hpp> unsigned int called = 0; struct my_at_thread_exit { typedef void result_type; explicit my_at_thread_exit(unsigned int& n) : m_called(&n) {} void operator() () const { ++(*m_called); } private: unsigned int* m_called; }; void my_thread_routine() { boost::sync::at_thread_exit(my_at_thread_exit(called)); } int main() { boost::thread t(&my_thread_routine); t.join(); BOOST_TEST_EQ(called, 1u); return boost::report_errors(); }
942
C++
.cpp
37
22.540541
65
0.668156
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
29,716
condition_variable_notify_all.cpp
supercollider_supercollider/external_libraries/boost_sync/test/run/condition_variable_notify_all.cpp
// Copyright (C) 2007 Anthony Williams // Copyright (C) 2013 Andrey Semashev // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/thread/thread.hpp> #include <boost/core/lightweight_test.hpp> #include "utils.hpp" #include "condition_test_common.hpp" unsigned const number_of_test_threads = 5; void do_test_condition_notify_all_wakes_from_wait() { wait_for_flag data; boost::thread_group group; try { for(unsigned i=0;i<number_of_test_threads;++i) { group.create_thread(bind_thread_func(&wait_for_flag::wait_without_predicate, data)); } { boost::sync::unique_lock<boost::sync::mutex> lock(data.mutex); data.flag=true; data.cond_var.notify_all(); } group.join_all(); BOOST_TEST_EQ(data.woken,number_of_test_threads); } catch(...) { group.join_all(); throw; } } void test_condition_notify_all_wakes_from_wait() { timed_test(&do_test_condition_notify_all_wakes_from_wait, timeout_seconds); } void do_test_condition_notify_all_wakes_from_wait_with_predicate() { wait_for_flag data; boost::thread_group group; try { for(unsigned i=0;i<number_of_test_threads;++i) { group.create_thread(bind_thread_func(&wait_for_flag::wait_with_predicate, data)); } { boost::sync::unique_lock<boost::sync::mutex> lock(data.mutex); data.flag=true; data.cond_var.notify_all(); } group.join_all(); BOOST_TEST_EQ(data.woken,number_of_test_threads); } catch(...) { group.join_all(); throw; } } void test_condition_notify_all_wakes_from_wait_with_predicate() { timed_test(&do_test_condition_notify_all_wakes_from_wait_with_predicate, timeout_seconds); } void do_test_condition_notify_all_wakes_from_timed_wait() { wait_for_flag data; boost::thread_group group; try { for(unsigned i=0;i<number_of_test_threads;++i) { group.create_thread(bind_thread_func(&wait_for_flag::timed_wait_without_predicate, data)); } { boost::sync::unique_lock<boost::sync::mutex> lock(data.mutex); data.flag=true; data.cond_var.notify_all(); } group.join_all(); BOOST_TEST_EQ(data.woken,number_of_test_threads); } catch(...) { group.join_all(); throw; } } void test_condition_notify_all_wakes_from_timed_wait() { timed_test(&do_test_condition_notify_all_wakes_from_timed_wait, timeout_seconds); } void do_test_condition_notify_all_wakes_from_timed_wait_with_predicate() { wait_for_flag data; boost::thread_group group; try { for(unsigned i=0;i<number_of_test_threads;++i) { group.create_thread(bind_thread_func(&wait_for_flag::timed_wait_with_predicate, data)); } { boost::sync::unique_lock<boost::sync::mutex> lock(data.mutex); data.flag=true; data.cond_var.notify_all(); } group.join_all(); BOOST_TEST_EQ(data.woken,number_of_test_threads); } catch(...) { group.join_all(); throw; } } void test_condition_notify_all_wakes_from_timed_wait_with_predicate() { timed_test(&do_test_condition_notify_all_wakes_from_timed_wait_with_predicate, timeout_seconds); } void do_test_condition_notify_all_wakes_from_relative_timed_wait_with_predicate() { wait_for_flag data; boost::thread_group group; try { for(unsigned i=0;i<number_of_test_threads;++i) { group.create_thread(bind_thread_func(&wait_for_flag::relative_timed_wait_with_predicate, data)); } { boost::sync::unique_lock<boost::sync::mutex> lock(data.mutex); data.flag=true; data.cond_var.notify_all(); } group.join_all(); BOOST_TEST_EQ(data.woken,number_of_test_threads); } catch(...) { group.join_all(); throw; } } void test_condition_notify_all_wakes_from_relative_timed_wait_with_predicate() { timed_test(&do_test_condition_notify_all_wakes_from_relative_timed_wait_with_predicate, timeout_seconds); } namespace { boost::sync::mutex multiple_wake_mutex; boost::sync::condition_variable multiple_wake_cond; unsigned multiple_wake_count = 0; void wait_for_condvar_and_increase_count() { boost::sync::unique_lock<boost::sync::mutex> lk(multiple_wake_mutex); multiple_wake_cond.wait(lk); ++multiple_wake_count; } } // namespace void do_test_notify_all_following_notify_one_wakes_all_threads() { boost::thread thread1(wait_for_condvar_and_increase_count); boost::thread thread2(wait_for_condvar_and_increase_count); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); multiple_wake_cond.notify_one(); boost::thread thread3(wait_for_condvar_and_increase_count); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); multiple_wake_cond.notify_one(); multiple_wake_cond.notify_all(); boost::this_thread::sleep(boost::posix_time::milliseconds(200)); { boost::sync::unique_lock<boost::sync::mutex> lk(multiple_wake_mutex); BOOST_TEST_EQ(multiple_wake_count, 3u); } thread1.join(); thread2.join(); thread3.join(); } void test_notify_all_following_notify_one_wakes_all_threads() { timed_test(&do_test_notify_all_following_notify_one_wakes_all_threads, timeout_seconds); } int main() { test_condition_notify_all_wakes_from_wait(); test_condition_notify_all_wakes_from_wait_with_predicate(); test_condition_notify_all_wakes_from_timed_wait(); test_condition_notify_all_wakes_from_timed_wait_with_predicate(); test_condition_notify_all_wakes_from_relative_timed_wait_with_predicate(); test_notify_all_following_notify_one_wakes_all_threads(); return boost::report_errors(); }
6,147
C++
.cpp
194
25.835052
109
0.654705
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
29,719
tss_windows.cpp
supercollider_supercollider/external_libraries/boost_sync/src/tss_windows.cpp
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * (C) Copyright 2004 Michael Glassford * (C) Copyright 2013 Andrey Semashev */ /*! * \file tss_windows.cpp * * \brief This header is the Boost.Sync library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/sync/doc/html/index.html. */ #include <boost/sync/detail/config.hpp> #if defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI) #include <cstddef> #include <cstdlib> #include <boost/detail/interlocked.hpp> #include <boost/sync/detail/tss.hpp> #include <boost/sync/condition_variables/notify_all_at_thread_exit.hpp> #include "tss_manager.hpp" #include "tss_windows_hooks.hpp" #include <windows.h> #include <boost/sync/detail/header.hpp> namespace boost { namespace sync { namespace detail { namespace { #if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 static INIT_ONCE init_tss_once_flag = INIT_ONCE_STATIC_INIT; #else static long init_tss_once_flag = 0; #endif static tss_manager* tss_mgr = NULL; #if defined(BOOST_SYNC_DETAIL_TLS) static BOOST_SYNC_DETAIL_TLS tss_manager::thread_context* tss_context = NULL; #else static DWORD tss_key = TLS_OUT_OF_INDEXES; #endif extern "C" { static BOOL WINAPI init_tss(void*, void*, void**) { windows::tss_cleanup_implemented(); // make sure the TSS cleanup hooks are linked into the executable try { tss_mgr = new tss_manager(); } catch (...) { std::abort(); } #if !defined(BOOST_SYNC_DETAIL_TLS) tss_key = TlsAlloc(); if (tss_key == TLS_OUT_OF_INDEXES) std::abort(); #endif return TRUE; } } // extern "C" #if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 BOOST_FORCEINLINE void init_tss_once() { InitOnceExecuteOnce(&init_tss_once_flag, (PINIT_ONCE_FN)&init_tss, NULL, NULL); } #else // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 BOOST_FORCEINLINE void init_tss_once() BOOST_NOEXCEPT { if (const_cast< long volatile& >(init_tss_once_flag) != 2) { while (true) { long old_val = BOOST_INTERLOCKED_COMPARE_EXCHANGE(&init_tss_once_flag, 1, 0); if (old_val == 2) break; else if (old_val == 1) SwitchToThread(); else { init_tss(NULL, NULL, NULL); BOOST_INTERLOCKED_EXCHANGE(&init_tss_once_flag, 2); break; } } } } #endif // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 #if defined(BOOST_SYNC_DETAIL_TLS) BOOST_FORCEINLINE tss_manager::thread_context* get_thread_context() BOOST_NOEXCEPT { return tss_context; } BOOST_FORCEINLINE void set_thread_context(tss_manager::thread_context* p) BOOST_NOEXCEPT { tss_context = p; } #else // defined(BOOST_SYNC_DETAIL_TLS) BOOST_FORCEINLINE tss_manager::thread_context* get_thread_context() BOOST_NOEXCEPT { return static_cast< tss_manager::thread_context* >(TlsGetValue(tss_key)); } BOOST_FORCEINLINE void set_thread_context(tss_manager::thread_context* p) BOOST_NOEXCEPT { TlsSetValue(tss_key, p); } #endif // defined(BOOST_SYNC_DETAIL_TLS) } // namespace namespace windows { void on_process_enter() { } void on_process_exit() { tss_manager* p = tss_mgr; tss_mgr = NULL; delete p; #if !defined(BOOST_SYNC_DETAIL_TLS) TlsFree(tss_key); tss_key = TLS_OUT_OF_INDEXES; #endif } void on_thread_enter() { } void on_thread_exit() { // This callback may be called before tss manager is initialized init_tss_once(); if (tss_manager::thread_context* ctx = get_thread_context()) { tss_mgr->destroy_thread_context(ctx); set_thread_context(NULL); } } } // namespace windows BOOST_SYNC_API void add_thread_exit_notify_entry(sync::mutex& mtx, sync::condition_variable& cond) { init_tss_once(); tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->add_notify_at_exit_entry(&mtx, &cond); } BOOST_SYNC_API void add_thread_exit_callback(at_thread_exit_callback callback, void* context) { init_tss_once(); tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->add_at_exit_entry(callback, context); } BOOST_SYNC_API thread_specific_key new_thread_specific_key(at_thread_exit_callback callback, bool cleanup_at_delete) { init_tss_once(); return tss_mgr->new_key(callback, cleanup_at_delete); } BOOST_SYNC_API void delete_thread_specific_key(thread_specific_key key) BOOST_NOEXCEPT { try { tss_mgr->delete_key(key); } catch (...) { std::abort(); } } BOOST_SYNC_API void* get_thread_specific(thread_specific_key key) BOOST_NOEXCEPT { tss_manager::thread_context* ctx = get_thread_context(); if (ctx) return ctx->get_value(key); return NULL; } BOOST_SYNC_API void set_thread_specific(thread_specific_key key, void* p) { tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->set_value(key, p); } } // namespace detail } // namespace sync } // namespace boost #include <boost/sync/detail/footer.hpp> #endif // defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI)
5,591
C++
.cpp
195
24.733333
116
0.680195
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
29,720
tss_pthread.cpp
supercollider_supercollider/external_libraries/boost_sync/src/tss_pthread.cpp
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * (C) Copyright 2004 Michael Glassford * (C) Copyright 2013 Andrey Semashev */ /*! * \file tss_pthread.cpp * * \brief This header is the Boost.Sync library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/sync/doc/html/index.html. */ #include <boost/sync/detail/config.hpp> #if !defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI) #include <cstddef> #include <cstdlib> #include <pthread.h> #include <boost/sync/detail/tss.hpp> #include <boost/sync/condition_variables/notify_all_at_thread_exit.hpp> #include "tss_manager.hpp" #include <boost/sync/detail/header.hpp> namespace boost { namespace sync { namespace detail { namespace { static pthread_once_t init_tss_once_flag = PTHREAD_ONCE_INIT; static tss_manager* tss_mgr = NULL; #if defined(BOOST_SYNC_DETAIL_TLS) static BOOST_SYNC_DETAIL_TLS tss_manager::thread_context* tss_context = NULL; #else static pthread_key_t tss_key; #endif extern "C" { static void tss_cleanup(void* p) { if (tss_manager::thread_context* ctx = static_cast< tss_manager::thread_context* >(p)) { tss_mgr->destroy_thread_context(ctx); } } static void init_tss() { try { tss_mgr = new tss_manager(); } catch (...) { std::abort(); } #if !defined(BOOST_SYNC_DETAIL_TLS) if (pthread_key_create(&tss_key, &tss_cleanup) != 0) std::abort(); #endif } } // extern "C" #if defined(BOOST_SYNC_DETAIL_TLS) BOOST_FORCEINLINE tss_manager::thread_context* get_thread_context() BOOST_NOEXCEPT { return tss_context; } BOOST_FORCEINLINE void set_thread_context(tss_manager::thread_context* p) BOOST_NOEXCEPT { tss_context = p; } #else // defined(BOOST_SYNC_DETAIL_TLS) BOOST_FORCEINLINE tss_manager::thread_context* get_thread_context() BOOST_NOEXCEPT { return static_cast< tss_manager::thread_context* >(pthread_getspecific(tss_key)); } BOOST_FORCEINLINE void set_thread_context(tss_manager::thread_context* p) BOOST_NOEXCEPT { pthread_setspecific(tss_key, p); } #endif // defined(BOOST_SYNC_DETAIL_TLS) } // namespace BOOST_SYNC_API void add_thread_exit_notify_entry(sync::mutex& mtx, sync::condition_variable& cond) { pthread_once(&init_tss_once_flag, &init_tss); tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->add_notify_at_exit_entry(&mtx, &cond); } BOOST_SYNC_API void add_thread_exit_callback(at_thread_exit_callback callback, void* context) { pthread_once(&init_tss_once_flag, &init_tss); tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->add_at_exit_entry(callback, context); } BOOST_SYNC_API thread_specific_key new_thread_specific_key(at_thread_exit_callback callback, bool cleanup_at_delete) { pthread_once(&init_tss_once_flag, &init_tss); return tss_mgr->new_key(callback, cleanup_at_delete); } BOOST_SYNC_API void delete_thread_specific_key(thread_specific_key key) BOOST_NOEXCEPT { try { tss_mgr->delete_key(key); } catch (...) { std::abort(); } } BOOST_SYNC_API void* get_thread_specific(thread_specific_key key) BOOST_NOEXCEPT { tss_manager::thread_context* ctx = get_thread_context(); if (ctx) return ctx->get_value(key); return NULL; } BOOST_SYNC_API void set_thread_specific(thread_specific_key key, void* p) { tss_manager::thread_context* ctx = get_thread_context(); if (!ctx) { ctx = tss_mgr->create_thread_context(); set_thread_context(ctx); } ctx->set_value(key, p); } } // namespace detail } // namespace sync } // namespace boost #include <boost/sync/detail/footer.hpp> #endif // !defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI)
4,080
C++
.cpp
138
26.246377
116
0.699437
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
29,721
tss_windows_dll.cpp
supercollider_supercollider/external_libraries/boost_sync/src/tss_windows_dll.cpp
// (C) Copyright Michael Glassford 2004. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/sync/detail/config.hpp> #if defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI) && defined(BOOST_SYNC_DYN_LINK) #include <windows.h> #include "tss_windows_hooks.hpp" #if defined(BOOST_BORLANDC) extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/) #elif defined(BOOST_EMBTC) extern "C" int _libmain(DWORD dwReason) #elif defined(_WIN32_WCE) extern "C" BOOL WINAPI DllMain(HANDLE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/) #else extern "C" BOOL WINAPI DllMain(HINSTANCE /*hInstance*/, DWORD dwReason, LPVOID /*lpReserved*/) #endif { switch(dwReason) { case DLL_PROCESS_ATTACH: { boost::sync::detail::windows::on_process_enter(); boost::sync::detail::windows::on_thread_enter(); break; } case DLL_THREAD_ATTACH: { boost::sync::detail::windows::on_thread_enter(); break; } case DLL_THREAD_DETACH: { boost::sync::detail::windows::on_thread_exit(); break; } case DLL_PROCESS_DETACH: { boost::sync::detail::windows::on_thread_exit(); boost::sync::detail::windows::on_process_exit(); break; } } return TRUE; } namespace boost { namespace sync { namespace detail { namespace windows { void tss_cleanup_implemented() { /* This function's sole purpose is to cause a link error in cases where automatic tss cleanup is not implemented by Boost.Threads as a reminder that user code is responsible for calling the necessary functions at the appropriate times (and for implementing an a tss_cleanup_implemented() function to eliminate the linker's missing symbol error). If Boost.Threads later implements automatic tss cleanup in cases where it currently doesn't (which is the plan), the duplicate symbol error will warn the user that their custom solution is no longer needed and can be removed. */ } } // namespace windows } // namespace detail } // namespace sync } // namespace boost #endif // defined(BOOST_SYNC_DETAIL_PLATFORM_WINAPI) && defined(BOOST_SYNC_DYN_LINK)
2,435
C++
.cpp
69
30.188406
100
0.689817
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
29,784
Common.cpp
supercollider_supercollider/QtCollider/Common.cpp
/************************************************************************ * * Copyright 2010 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "Common.h" #include "metatype.hpp" #include <PyrKernel.h> #include <VMGlobals.h> #include <PyrLexer.h> // WARNING: QtCollider::lockLang() must be called before void QtCollider::runLang(PyrObjectHdr* receiver, PyrSymbol* method, const QList<QVariant>& args, PyrSlot* result) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; ++g->sp; SetObject(g->sp, receiver); Q_FOREACH (QVariant var, args) { ++g->sp; if (!QtCollider::set(g->sp, var)) { qcErrorMsg("Failed to write a slot when trying to run interpreter!"); SetNil(g->sp); } } runInterpreter(g, method, args.size() + 1); g->canCallOS = false; if (result) slotCopy(result, &g->result); } int QtCollider::wrongThreadError() { qcErrorMsg("You can not use this Qt functionality in the current thread. " "Try scheduling on AppClock instead."); return errFailed; }
1,849
C++
.cpp
48
34.645833
115
0.642738
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,785
type_codec.cpp
supercollider_supercollider/QtCollider/type_codec.cpp
/************************************************************************ * * Copyright 2010 - 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "type_codec.hpp" #include "metatype.hpp" #include "QObjectProxy.h" #include "widgets/QcTreeWidget.h" #include "primitives/prim_QPalette.hpp" #include "image.h" #include <PyrObject.h> #include <PyrKernel.h> #include <GC.h> #include <VMGlobals.h> #include <qmath.h> namespace QtCollider { QString TypeCodec<QString>::read(PyrSlot* slot) { if (IsSym(slot)) { return QString::fromUtf8(slotRawSymbol(slot)->name); } else if (isKindOfSlot(slot, class_string)) { int len = slotRawObject(slot)->size; return QString::fromUtf8(slotRawString(slot)->s, len); } return QString(); } void TypeCodec<QString>::write(PyrSlot* slot, const QString& val) { PyrString* str = newPyrString(gMainVMGlobals->gc, val.toUtf8().constData(), 0, true); SetObject(slot, str); } QUrl TypeCodec<QUrl>::read(PyrSlot* slot) { if (IsSym(slot)) { return QUrl(QString::fromUtf8(slotRawSymbol(slot)->name)); } else if (isKindOfSlot(slot, class_string)) { int len = slotRawObject(slot)->size; return QUrl(QString::fromUtf8(slotRawString(slot)->s, len)); } else { return QUrl(); } } void TypeCodec<QUrl>::write(PyrSlot* slot, const QUrl& val) { PyrString* str = newPyrString(gMainVMGlobals->gc, val.toString(QUrl::None).toUtf8().constData(), 0, true); SetObject(slot, str); } QPointF TypeCodec<QPointF>::read(PyrSlot* slot) { PyrSlot* slots = slotRawObject(slot)->slots; float x, y; int err; err = slotFloatVal(slots + 0, &x); if (err) return QPointF(); err = slotFloatVal(slots + 1, &y); if (err) return QPointF(); return QPointF(x, y); } QPointF TypeCodec<QPointF>::safeRead(PyrSlot* slot) { if (isKindOfSlot(slot, SC_CLASS(Point))) return read(slot); else return QPointF(); } void TypeCodec<QPointF>::write(PyrSlot* slot, const QPointF& pt) { PyrObject* obj = instantiateObject(gMainVMGlobals->gc, SC_CLASS(Point), 0, true, true); SetObject(slot, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, pt.x()); SetFloat(slots + 1, pt.y()); } QRectF TypeCodec<QRectF>::read(PyrSlot* slot) { PyrSlot* slots = slotRawObject(slot)->slots; float bounds[4]; for (int i = 0; i < 4; ++i) { int err = slotFloatVal(slots + i, &bounds[i]); if (err) return QRectF(); } return QRectF(bounds[0], bounds[1], bounds[2], bounds[3]); } QRectF TypeCodec<QRectF>::safeRead(PyrSlot* slot) { if (isKindOfSlot(slot, SC_CLASS(Rect))) return read(slot); else return QRectF(); } void TypeCodec<QRectF>::write(PyrSlot* slot, const QRectF& r) { PyrObject* obj = instantiateObject(gMainVMGlobals->gc, SC_CLASS(Rect), 0, true, true); SetObject(slot, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, r.x()); SetFloat(slots + 1, r.y()); SetFloat(slots + 2, r.width()); SetFloat(slots + 3, r.height()); } QSizeF TypeCodec<QSizeF>::read(PyrSlot* slot) { PyrSlot* slots = slotRawObject(slot)->slots; float w = 0.f, h = 0.f; slotFloatVal(slots + 0, &w); slotFloatVal(slots + 1, &h); return QSizeF(w, h); } QSizeF TypeCodec<QSizeF>::safeRead(PyrSlot* slot) { if (isKindOfSlot(slot, SC_CLASS(Size))) return read(slot); else return QSizeF(); } void TypeCodec<QSizeF>::write(PyrSlot* slot, const QSizeF& sz) { PyrObject* obj = instantiateObject(gMainVMGlobals->gc, SC_CLASS(Size), 0, true, true); SetObject(slot, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, sz.width()); SetFloat(slots + 1, sz.height()); } inline QColor asColor(PyrObject* obj) { PyrSlot* slots = obj->slots; float r, g, b, a; r = g = b = a = 0.f; slotFloatVal(slots + 0, &r); slotFloatVal(slots + 1, &g); slotFloatVal(slots + 2, &b); slotFloatVal(slots + 3, &a); return QColor(r * 255, g * 255, b * 255, a * 255); } QColor TypeCodec<QColor>::read(PyrSlot* slot) { PyrObject* obj = slotRawObject(slot); PyrClass* klass = obj->classptr; if (klass == SC_CLASS(Color)) return asColor(obj); if (klass == SC_CLASS(Gradient) || klass == SC_CLASS(HiliteGradient)) { qcWarningMsg("WARNING: Gradient and HiliteGradient are not supported yet." " Using the average gradient color instead."); QColor c1(safeRead(obj->slots + 0)); QColor c2(safeRead(obj->slots + 1)); QColor mix((c1.red() + c2.red()) / 2, (c1.green() + c2.green()) / 2, (c1.blue() + c2.blue()) / 2); return mix; } return QColor(); } void TypeCodec<QColor>::write(PyrSlot* slot, const QColor& c) { if (!c.isValid()) { SetNil(slot); return; } PyrObject* obj = instantiateObject(gMainVMGlobals->gc, SC_CLASS(Color), 0, true, true); SetObject(slot, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, c.red() / 255.0); SetFloat(slots + 1, c.green() / 255.0); SetFloat(slots + 2, c.blue() / 255.0); SetFloat(slots + 3, c.alpha() / 255.0); } QFont TypeCodec<QFont>::read(PyrSlot* slot) { PyrSlot* slots = slotRawObject(slot)->slots; QString family = TypeCodec<QString>::safeRead(slots + 0); float fSize = TypeCodec<float>::safeRead(slots + 1); bool bold = TypeCodec<bool>::safeRead(slots + 2); bool italic = TypeCodec<bool>::safeRead(slots + 3); bool isPtSize = TypeCodec<bool>::safeRead(slots + 4); QFont f; if (!family.isEmpty()) f.setFamily(family); if (fSize > 0.f) { if (isPtSize) { f.setPointSizeF(fSize); } else { int pixSize = (fSize > 1.f ? qRound(fSize) : 1); f.setPixelSize(pixSize); } } f.setBold(bold); f.setItalic(italic); return f; } QFont TypeCodec<QFont>::safeRead(PyrSlot* slot) { if (isKindOfSlot(slot, SC_CLASS(Font))) return TypeCodec<QFont>::read(slot); else return QFont(); } QPalette TypeCodec<QPalette>::read(PyrSlot* slot) { QPalette* p = QPALETTE_FROM_OBJECT(slotRawObject(slot)); return *p; } QPalette TypeCodec<QPalette>::safeRead(PyrSlot* slot) { if (isKindOfSlot(slot, SC_CLASS(QPalette))) return TypeCodec<QPalette>::read(slot); else return QPalette(); } void TypeCodec<QPalette>::write(PyrSlot* slot, const QPalette& plt) { PyrGC* gc = gMainVMGlobals->gc; PyrObject* obj = instantiateObject(gc, SC_CLASS(QPalette), 0, true, true); SetObject(slot, obj); QPalette_Init(gMainVMGlobals, obj, plt); } QObjectProxy* TypeCodec<QObjectProxy*>::safeRead(PyrSlot* slot) { if (!isKindOfSlot(slot, SC_CLASS(QObject))) return 0; return read(slot); } void TypeCodec<QObject*>::write(PyrSlot* slot, QObject* obj) { QObjectProxy* proxy = QObjectProxy::fromObject(obj); if (proxy && proxy->scObject()) SetObject(slot, proxy->scObject()); else SetNil(slot); } QVariantList TypeCodec<QVariantList>::read(PyrSlot* slot) { if (isKindOfSlot(slot, class_array)) { PyrObject* obj = slotRawObject(slot); PyrSlot* slots = obj->slots; int size = obj->size; QVariantList list; for (int i = 0; i < size; ++i, ++slots) { list << QtCollider::get<QVariant>(slots); } return list; } else if (isKindOfSlot(slot, class_symbolarray)) { PyrSymbolArray* symarray = slotRawSymbolArray(slot); PyrSymbol** symbols = symarray->symbols; int size = symarray->size; QVariantList list; for (int i = 0; i < size; ++i, ++symbols) list << QVariant(QString((*symbols)->name)); return list; } return QVariantList(); } void TypeCodec<QVariantList>::write(PyrSlot* slot, const QVariantList& varList) { VMGlobals* g = gMainVMGlobals; int count = varList.count(); PyrObject* array = newPyrArray(g->gc, count, 0, true); SetObject(slot, array); int i; PyrSlot* s = array->slots; for (i = 0; i < count; ++i, ++s) { if (!QtCollider::set(s, varList[i])) { qcDebugMsg(1, "WARNING: Could not set one slot of array"); } array->size++; g->gc->GCWrite(array, s); } } #define WRONG_OBJECT_FORMAT false template <typename DEST, typename ORIG> inline static void copy(QVector<DEST>& dest, PyrSlot* orig, int size) { ORIG* array = (ORIG*)orig; for (int i = 0; i < size; ++i) dest << DEST(array[i]); } template <typename numeric_type> static QVector<numeric_type> toNumericVector(PyrObject* obj) { int size = obj->size; PyrSlot* slots = obj->slots; QVector<numeric_type> vector; vector.reserve(size); switch (obj->obj_format) { case obj_double: copy<numeric_type, double>(vector, slots, size); break; case obj_float: copy<numeric_type, float>(vector, slots, size); break; case obj_int32: copy<numeric_type, int32>(vector, slots, size); break; case obj_int16: copy<numeric_type, int16>(vector, slots, size); break; case obj_int8: copy<numeric_type, int8>(vector, slots, size); break; default: Q_ASSERT(WRONG_OBJECT_FORMAT); } return vector; } template <typename numeric_type> static void setNumeric(PyrSlot*, numeric_type); template <> inline void setNumeric<double>(PyrSlot* s, double val) { SetFloat(s, val); } template <> inline void setNumeric<int>(PyrSlot* s, int val) { SetInt(s, val); } template <typename numeric_type> static void setNumericVector(PyrSlot* slot, const QVector<numeric_type>& vec) { VMGlobals* g = gMainVMGlobals; int count = vec.count(); PyrObject* array = newPyrArray(g->gc, count, 0, true); SetObject(slot, array); PyrSlot* s = array->slots; Q_FOREACH (numeric_type val, vec) { setNumeric<numeric_type>(s, val); ++array->size; ++s; } } QVector<double> TypeCodec<QVector<double>>::read(PyrSlot* slot) { return toNumericVector<double>(slotRawObject(slot)); } void TypeCodec<QVector<double>>::write(PyrSlot* slot, const QVector<double>& vec) { setNumericVector<double>(slot, vec); } QVector<int> TypeCodec<QVector<int>>::read(PyrSlot* slot) { return toNumericVector<int>(slotRawObject(slot)); } void TypeCodec<QVector<int>>::write(PyrSlot* slot, const QVector<int>& vec) { setNumericVector<int>(slot, vec); } QcTreeWidget::ItemPtr TypeCodec<QcTreeWidget::ItemPtr>::read(PyrSlot* slot) { PyrSlot* ptrSlot = slotRawObject(slot)->slots + 0; if (IsPtr(ptrSlot)) { QcTreeWidget::ItemPtr* safePtr = static_cast<QcTreeWidget::ItemPtr*>(slotRawPtr(ptrSlot)); return *safePtr; } else { return QcTreeWidget::ItemPtr(); } } void TypeCodec<QcTreeWidget::ItemPtr>::write(PyrSlot* slot, const QcTreeWidget::ItemPtr& item) { PyrObject* obj = instantiateObject(gMainVMGlobals->gc, SC_CLASS(TreeViewItem), 0, true, true); QcTreeWidget::Item::initialize(gMainVMGlobals, obj, item); SetObject(slot, obj); } SharedImage TypeCodec<SharedImage>::read(PyrSlot* slot) { SharedImage* ptr = reinterpret_cast<SharedImage*>(slotRawPtr(slotRawObject(slot)->slots + 0)); return *ptr; } SharedImage TypeCodec<SharedImage>::safeRead(PyrSlot* slot) { if (!isKindOfSlot(slot, SC_CLASS(Image))) return SharedImage(); else return read(slot); } void TypeCodec<SharedImage>::write(PyrSlot* slot, SharedImage image) { qWarning("WARNING: QtCollider: writing SharedImage to PyrSlot not supported."); } } // namespace QtCollider
12,552
C++
.cpp
341
31.651026
120
0.649401
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,786
LanguageClient.cpp
supercollider_supercollider/QtCollider/LanguageClient.cpp
/************************************************************************ * * Copyright 2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "LanguageClient.h" #include "QcApplication.h" #include "QtCollider.h" #include "QObjectProxy.h" #include <PyrKernel.h> #include <PyrLexer.h> #include <qmath.h> #include <QWidget> extern double elapsedTime(); using namespace QtCollider; LangClient::LangClient(const char* name): SC_TerminalClient(name) {} void LangClient::commandLoop() { int exit_code = QcApplication::instance()->exec(); SC_TerminalClient::quit(exit_code); } void LangClient::daemonLoop() { commandLoop(); } void LangClient::sendSignal(Signal sig) { if (sig == sig_sched) { QApplication::postEvent(this, new SCRequestEvent(Event_SCRequest_Tick)); } else { SC_TerminalClient::sendSignal(sig); QApplication::postEvent(this, new SCRequestEvent(Event_SCRequest_Work)); } } void LangClient::onQuit(int exitCode) { QApplication::postEvent(this, new SCRequestEvent(Event_SCRequest_Quit, exitCode)); } void LangClient::onLibraryShutdown() { QWidgetList windows = QApplication::topLevelWidgets(); Q_FOREACH (QWidget* w, windows) w->hide(); } void LangClient::customEvent(QEvent* e) { int type = e->type(); switch (type) { case Event_SCRequest_Tick: tick(); case Event_SCRequest_Work: QApplication::removePostedEvents(this, Event_SCRequest_Work); mIoService.poll(); break; case Event_SCRequest_Quit: { int code = static_cast<SCRequestEvent*>(e)->data.toInt(); qcDebugMsg(1, QStringLiteral("Quit requested with code %1").arg(code)); qApp->exit(code); break; } default:; } } void LangClient::tick() { double secs; lock(); // deadlock here indicates behaviour which likely should be avoided. // e.g. calling qt event loop from primitive. bool haveNext = tickLocked(&secs); unlock(); flush(); if (haveNext) { secs -= elapsedTime(); secs *= 1000; int ti = qMax(0, qCeil(secs)); qcDebugMsg(2, QStringLiteral("next at %1").arg(ti)); appClockTimer.start(ti, this); } else appClockTimer.stop(); } void LangClient::timerEvent(QTimerEvent* e) { if (e->timerId() == appClockTimer.timerId()) tick(); }
3,138
C++
.cpp
91
30.252747
86
0.661823
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,787
metatype.cpp
supercollider_supercollider/QtCollider/metatype.cpp
/************************************************************************ * * Copyright 2010 - 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "metatype.hpp" #include "type_codec.hpp" #include "Common.h" // Make sure PyrObject* is declared to QMetaType #include <PyrKernel.h> #include "QcCallback.hpp" namespace QtCollider { static QVector<MetaType*> gMetaTypes; template <typename T> MetaTypeImpl<T>* MetaTypeImpl<T>::instance = 0; template <typename T> void qc_init_metatype() { MetaTypeImpl<T>::instance = new MetaTypeImpl<T>(); gMetaTypes.append(MetaTypeImpl<T>::instance); } void MetaType::initAll() { qRegisterMetaType<PyrObject*>(); qRegisterMetaType<QObjectProxy*>(); qRegisterMetaType<QcTreeWidget::ItemPtr>(); qRegisterMetaType<QVector<double>>(); qRegisterMetaType<QVector<int>>(); qRegisterMetaType<SharedImage>(); qRegisterMetaType<QcAction*>(); qRegisterMetaType<QcWidgetAction*>(); qRegisterMetaType<QcMenu*>(); qRegisterMetaType<QcToolBar*>(); qRegisterMetaType<QList<QAction*>>(); gMetaTypes.reserve(30); qc_init_metatype<bool>(); qc_init_metatype<int>(); qc_init_metatype<float>(); qc_init_metatype<double>(); qc_init_metatype<QChar>(); qc_init_metatype<QString>(); qc_init_metatype<QPointF>(); qc_init_metatype<QPoint>(); qc_init_metatype<QSizeF>(); qc_init_metatype<QSize>(); qc_init_metatype<QRectF>(); qc_init_metatype<QRect>(); qc_init_metatype<QColor>(); qc_init_metatype<QFont>(); qc_init_metatype<QPalette>(); qc_init_metatype<QObjectProxy*>(); qc_init_metatype<QObject*>(); qc_init_metatype<QWidget*>(); qc_init_metatype<QLayout*>(); qc_init_metatype<PyrObject*>(); qc_init_metatype<QcTreeWidget::ItemPtr>(); qc_init_metatype<SharedImage>(); qc_init_metatype<QMenu*>(); qc_init_metatype<QAction*>(); qc_init_metatype<QList<QAction*>>(); qc_init_metatype<QVector<double>>(); qc_init_metatype<QVector<int>>(); qc_init_metatype<QVariantList>(); qc_init_metatype<QUrl>(); qc_init_metatype<QcCallback*>(); } MetaType* MetaType::find(PyrSlot* slot) { switch (GetTag(slot)) { case tagNil: return 0; case tagInt: return metaType<int>(); case tagSym: return metaType<QString>(); case tagChar: return metaType<QChar>(); case tagFalse: case tagTrue: return metaType<bool>(); case tagObj: { PyrObject* obj = slotRawObject(slot); PyrClass* klass = obj->classptr; unsigned char format = obj->obj_format; if (format == obj_double || format == obj_float) return metaType<QVector<double>>(); else if (format == obj_int32 || format == obj_int16 || format == obj_int8) return metaType<QVector<int>>(); else if (isKindOfSlot(slot, class_string)) { return metaType<QString>(); } else if (isKindOfSlot(slot, SC_CLASS(Point))) { return metaType<QPointF>(); } else if (isKindOfSlot(slot, SC_CLASS(Rect))) { return metaType<QRectF>(); } else if (isKindOfSlot(slot, SC_CLASS(Size))) { return metaType<QSizeF>(); } else if (klass == SC_CLASS(Color) || klass == SC_CLASS(Gradient) || klass == SC_CLASS(HiliteGradient)) { return metaType<QColor>(); } else if (isKindOfSlot(slot, SC_CLASS(Font))) { return metaType<QFont>(); } else if (isKindOfSlot(slot, SC_CLASS(QPalette))) { return metaType<QPalette>(); } else if (isKindOfSlot(slot, SC_CLASS(QCallback))) { return metaType<QcCallback*>(); } else if (isKindOfSlot(slot, SC_CLASS(AbstractMenuAction))) { return metaType<QAction*>(); } else if (isKindOfSlot(slot, SC_CLASS(Menu))) { return metaType<QMenu*>(); } else if (isKindOfSlot(slot, SC_CLASS(View)) || isKindOfSlot(slot, SC_CLASS(ScrollCanvas))) { return metaType<QWidget*>(); } else if (isKindOfSlot(slot, SC_CLASS(Layout))) { return metaType<QLayout*>(); } else if (isKindOfSlot(slot, SC_CLASS(QObject))) { return metaType<QObjectProxy*>(); } else if (isKindOfSlot(slot, class_array) || isKindOfSlot(slot, class_symbolarray)) { return metaType<QVariantList>(); } else if (isKindOfSlot(slot, SC_CLASS(TreeViewItem))) { return metaType<QcTreeWidget::ItemPtr>(); } else if (isKindOfSlot(slot, SC_CLASS(Image))) { return metaType<SharedImage>(); } else { QString className = TypeCodec<QString>::read(&slotRawObject(slot)->classptr->name); qcWarningMsg(QStringLiteral("WARNING: Do not know how to use an instance of class '%1'").arg(className)); return 0; } } default: return metaType<double>(); } } MetaType* MetaType::find(int id) { int n = gMetaTypes.count(); MetaType* const* d = gMetaTypes.constData(); int i; for (i = 0; i < n; ++i) { if ((*d)->mId == id) return *d; ++d; } return 0; } } // namespace QtCollider
5,973
C++
.cpp
151
33.311258
117
0.62963
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,788
QcCallback.cpp
supercollider_supercollider/QtCollider/QcCallback.cpp
/* SuperCollider Language Copyright (c) 2018 SuperCollider Team https://supercollider.github.io/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "QcCallback.hpp" #include "QcObjectFactory.h" QC_DECLARE_QOBJECT_FACTORY(QcCallback);
934
C++
.cpp
19
44.947368
81
0.765934
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,789
QcApplication.cpp
supercollider_supercollider/QtCollider/QcApplication.cpp
/************************************************************************ * * Copyright 2010 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcApplication.h" #include "widgets/QcTreeWidget.h" #include <PyrLexer.h> #include <VMGlobals.h> #include <PyrKernel.h> #include <PyrSlot.h> #include <GC.h> #include "SC_Filesystem.hpp" #include <QThread> #include <QFileOpenEvent> #include <QKeyEvent> #include <QIcon> #include <QMenuBar> #include <QSharedPointer> #include "hacks/hacks_mac.hpp" #ifdef Q_OS_MAC # include "../../common/SC_Apple.hpp" #endif extern bool compiledOK; QcApplication* QcApplication::_instance = 0; QMutex QcApplication::_mutex; #ifdef Q_WS_X11 # include <X11/Xlib.h> #endif /* on x11, we need to check, if we can actually connect to the X server */ static bool QtColliderUseGui(void) { #ifdef Q_WS_X11 Display* dpy = XOpenDisplay(NULL); if (!dpy) return false; XCloseDisplay(dpy); return true; #else return true; #endif } // undefine some interfering X11 definitions #undef KeyPress bool QcApplication::_systemHasMouseWheel = false; QcApplication::QcApplication(int& argc, char** argv): QApplication(argc, argv, QtColliderUseGui()) { _mutex.lock(); _instance = this; _mutex.unlock(); this->setAttribute(Qt::AA_UseHighDpiPixmaps); #ifdef Q_OS_MAC QtCollider::Mac::DisableAutomaticWindowTabbing(); #endif if (QtColliderUseGui()) { // avoid a crash on linux, if x is not available QIcon icon; icon.addFile(":/icons/sc-cube-128"); icon.addFile(":/icons/sc-cube-48"); icon.addFile(":/icons/sc-cube-32"); icon.addFile(":/icons/sc-cube-16"); setWindowIcon(icon); createMenu(); } #ifdef Q_OS_MAC // On Mac, we may need to disable "App Nap", so we aren't put to sleep unexpectedly SC::Apple::disableAppNap(); #endif _handleCmdPeriod = SC_Filesystem::instance().getIdeName() != "scapp"; } QcApplication::~QcApplication() { _mutex.lock(); _instance = 0; _mutex.unlock(); } void QcApplication::createMenu() { _mainMenu = QSharedPointer<QMenuBar>::create(); #ifdef Q_OS_MAC // macOS registers cmd+q on menu bars by default. Here we register a handler for cmd+q that does nothing // and we disable the Quit menu by default auto* action = new QAction(""); action->setMenuRole(QAction::QuitRole); action->setEnabled(false); QObject::connect(action, SIGNAL(triggered()), this, SLOT(onQuit())); auto* menu = new QMenu(tr("&File")); menu->addAction(action); _mainMenu->addMenu(menu); #endif } void QcApplication::onQuit() { qWarning("[QcApplication::onQuit] CMD+Q was caught by the interpreter. " "This is weird, it should not happen. " "Please file an issue at https://github.com/supercollider/supercollider/issues"); } bool QcApplication::compareThread() { return gMainVMGlobals->canCallOS; } void QcApplication::interpret(const QString& str, bool print) { QtCollider::lockLang(); if (compiledOK) { VMGlobals* g = gMainVMGlobals; PyrString* strObj = newPyrString(g->gc, str.toStdString().c_str(), 0, true); SetObject(&slotRawInterpreter(&g->process->interpreter)->cmdLine, strObj); g->gc->GCWriteNew(slotRawObject(&g->process->interpreter), strObj); // we know strObj is white so we can use GCWriteNew runLibrary(print ? SC_SYM(interpretPrintCmdLine) : SC_SYM(interpretCmdLine)); } QtCollider::unlockLang(); } bool QcApplication::event(QEvent* event) { switch (event->type()) { case QEvent::FileOpen: { // open the file dragged onto the application icon on Mac QFileOpenEvent* fe = static_cast<QFileOpenEvent*>(event); interpret(QStringLiteral("Document.open(\"%1\")").arg(fe->file()), false); event->accept(); return true; } default: break; } return QApplication::event(event); } bool QcApplication::notify(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::KeyPress: { QKeyEvent* kevent = static_cast<QKeyEvent*>(event); if (_handleCmdPeriod && (kevent->key() == Qt::Key_Period) && (kevent->modifiers() & Qt::ControlModifier)) { static QString cmdPeriodCommand("CmdPeriod.run"); interpret(cmdPeriodCommand, false); } break; } case QEvent::Wheel: { _systemHasMouseWheel = true; break; } default: break; } bool result = QApplication::notify(object, event); #ifdef Q_OS_MAC // XXX Explicitly accept all handled events so they don't propagate outside the application. // This is a hack; for a not-fully-understood reason Qt past 5.7 sends these events to the // native window if they aren't accepted here. This caused issue #4058. Accepting them here // seems to solve the problem, but might cause other issues since it is a heavy-handed way // of doing this. // In order to still allow closing GUI windows with "cmd-w", we need to let through both // this key combination, as well as modifier keys alone, since the "cmd" needs to be passed // through by itself first for the "cmd-w" to work. // TODO - solve more elegantly if (result && event->type() == QEvent::KeyPress) { auto kevent = static_cast<QKeyEvent*>(event); if (!((kevent->key() == Qt::Key_W) && (kevent->modifiers() == Qt::ControlModifier)) && (kevent->key() != Qt::Key_unknown)) { event->accept(); } } #endif return result; }
6,392
C++
.cpp
171
32.766082
115
0.665428
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,790
interface.cpp
supercollider_supercollider/QtCollider/interface.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QtCollider.h" #include "QcApplication.h" #include "Common.h" #include "style/ProxyStyle.hpp" #include "style/style.hpp" #include "metatype.hpp" #include <QTimer> #include <QEventLoop> #include <QDir> #ifdef SC_USE_QTWEBENGINE # include <QWebEngineSettings> # include <QWebEngineProfile> #endif #ifdef Q_WS_X11 # include <X11/Xlib.h> #endif #include <clocale> namespace QtCollider { void loadFactories(); } inline void initResources() { Q_INIT_RESOURCE(resources); } static QPalette gSystemPalette; QPalette QtCollider::systemPalette() { return gSystemPalette; } void QtCollider::init() { if (!QApplication::instance()) { qcDebugMsg(1, "Initializing QtCollider"); initResources(); QtCollider::loadFactories(); QtCollider::MetaType::initAll(); QLocale::setDefault(QLocale::c()); #ifdef Q_WS_X11 XInitThreads(); #endif #ifdef Q_OS_MAC // TODO: this should not be necessary QApplication::setAttribute(Qt::AA_PluginApplication, true); #endif static int qcArgc = 1; static char qcArg0[] = "SuperCollider"; static char* qcArgv[1] = { qcArg0 }; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif // In order to scale the UI properly on Windows with display scaling like 125% or 150% // we need to disable scale factor rounding QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); QcApplication* qcApp = new QcApplication(qcArgc, qcArgv); qcApp->setQuitOnLastWindowClosed(false); // qcApp->setStyle( new QtCollider::Style::StyleImpl( new QPlastiqueStyle ) ); gSystemPalette = qcApp->palette(); #ifdef SC_USE_QTWEBENGINE // Enable javascript localStorage for WebViews QWebEngineProfile::defaultProfile()->settings()->setAttribute(QWebEngineSettings::LocalStorageEnabled, true); #endif // NOTE: Qt may tamper with the C language locale, affecting POSIX number-string conversions. // Revert the locale to default: setlocale(LC_NUMERIC, "C"); } } int QtCollider::exec(int argc, char** argv) { QtCollider::init(); Q_ASSERT(qApp); return qApp->exec(); }
3,220
C++
.cpp
84
34.297619
117
0.687661
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,791
QObjectProxy.cpp
supercollider_supercollider/QtCollider/QObjectProxy.cpp
/************************************************************************ * * Copyright 2010-2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include <QDebug> #include "QObjectProxy.h" #include "QcApplication.h" #include "Common.h" #include "QcSignalSpy.h" #include "type_codec.hpp" #include "metatype.hpp" #include <QApplication> #include <QWidget> #include <QVarLengthArray> #include <QThread> #include <PyrKernel.h> #include <VMGlobals.h> #if defined _WIN32 # include "SC_Win32Utils.h" #elif defined __FreeBSD__ || defined __OpenBSD__ # include <stdlib.h> #else # include <alloca.h> #endif using namespace QtCollider; void interpretMouseEvent(QEvent* e, QList<QVariant>& args); void interpretKeyEvent(QEvent* e, QList<QVariant>& args); QObjectProxy::QObjectProxy(QObject* qObject_, PyrObject* scObject_): qObject(qObject_), _scObject(scObject_), _scClassName(slotRawSymbol(&scObject_->classptr->name)->name) { ProxyToken* token = new ProxyToken(this, qObject); // WARNING: make sure the signal is already in normalized signature, // to avoid triggering very expensive normalization! connect(qObject, SIGNAL(destroyed(QObject*)), this, SLOT(invalidate())); qObject->installEventFilter(this); _eventHandlers.reserve(10); } QObjectProxy::~QObjectProxy() { qcProxyDebugMsg(1, QStringLiteral("Proxy is being deleted.")); } bool QObjectProxy::compareThread() { return gMainVMGlobals->canCallOS; } void QObjectProxy::invalidate() { qcProxyDebugMsg(1, QStringLiteral("Object has been deleted. Invalidating proxy.")); mutex.lock(); qObject = 0; mutex.unlock(); QApplication::postEvent(this, new QEvent((QEvent::Type)QtCollider::Event_Proxy_Release)); } static bool serializeSignature(QVarLengthArray<char, 512>& dst, const char* method, int argc, MetaValue* argv) { // serialize method name int len = qstrlen(method); if (len <= 0) { qcErrorMsg("Method name appears to be empty."); return false; } dst.append(method, len); dst.append('('); // serialize argument types int i; for (i = 0; i < argc; ++i) { int typeId = argv[i].type()->id(); const char* typeName = QMetaType(typeId).name(); int len = qstrlen(typeName); if (len <= 0) { qcErrorMsg("Could not get argument type name."); return false; } dst.append(typeName, len); dst.append(','); } // finalize the signature if (i == 0) dst.append(')'); else dst[dst.size() - 1] = ')'; dst.append('\0'); return true; } bool QObjectProxy::invokeMethod(const char* method, PyrSlot* retSlot, PyrSlot* argSlot, Qt::ConnectionType ctype) { QMutexLocker locker(&mutex); if (!qObject) return true; MetaValue args[10]; PyrSlot* argslots; int argc; if (isKindOfSlot(argSlot, class_array)) { argslots = slotRawObject(argSlot)->slots; argc = slotRawObject(argSlot)->size; } else if (argSlot && NotNil(argSlot)) { argslots = argSlot; argc = 1; } else { argslots = 0; argc = 0; } // translate args for (int i = 0; i < argc; ++i) { MetaType* type = MetaType::find(argslots + i); if (!type) return false; void* mem = alloca(type->size()); if (!mem) { qcErrorMsg("Could not allocate stack space for argument!"); return false; } args[i].read(mem, type, argslots + i); } // serialize signature QVarLengthArray<char, 512> sig; if (!serializeSignature(sig, method, argc, args)) return false; // get the meta method const QMetaObject* mo = qObject->metaObject(); int mi = mo->indexOfMethod(sig.constData()); if (mi < 0) { QByteArray mnorm = QMetaObject::normalizedSignature(sig.constData()); mi = mo->indexOfMethod(mnorm.constData()); } if (mi < 0 || mi >= mo->methodCount()) { qcProxyDebugMsg(1, QStringLiteral("WARNING: No such method: %1::%2").arg(mo->className()).arg(sig.constData())); return false; } QMetaMethod mm = mo->method(mi); // construct the return data object QGenericReturnArgument rarg; const char* rtype_name = mm.typeName(); int rtype_id = QMetaType::type(rtype_name); MetaValue returnVal; if (retSlot && rtype_id != QMetaType::Void) { MetaType* type = MetaType::find(rtype_id); if (!type) { qcErrorMsg(QStringLiteral("No translation for return type '%1'").arg(rtype_name)); return false; } void* mem = alloca(type->size()); if (!mem) { qcErrorMsg("Could not allocate stack space for return value"); return false; } returnVal.read(mem, type, 0); // default construction rarg = returnVal.toGenericReturnArgument(); } // do it! bool success = mm.invoke(qObject, ctype, rarg, args[0].toGenericArgument(), args[1].toGenericArgument(), args[2].toGenericArgument(), args[3].toGenericArgument(), args[4].toGenericArgument(), args[5].toGenericArgument(), args[6].toGenericArgument(), args[7].toGenericArgument(), args[8].toGenericArgument(), args[9].toGenericArgument()); // store the return data into the return slot if (success && retSlot) returnVal.write(retSlot); // done return success; } void QObjectProxy::invokeScMethod(PyrSymbol* method, const QList<QVariant>& args, PyrSlot* result, bool locked) { qcProxyDebugMsg(1, QStringLiteral("SC METHOD CALL [+++]: ") + QString(method->name)); if (!locked) { QtCollider::lockLang(); } if (_scObject) { QtCollider::runLang(_scObject, method, args, result); } else { if (result) SetNil(result); qcDebugMsg(1, "WARNING: no SC object"); } if (!locked) QtCollider::unlockLang(); qcProxyDebugMsg(1, QStringLiteral("SC METHOD CALL [---]: ") + QString(method->name)); } void QObjectProxy::customEvent(QEvent* event) { switch ((int)event->type()) { case QtCollider::Event_ScMethodCall: scMethodCallEvent(static_cast<ScMethodCallEvent*>(event)); return; case QtCollider::Event_Proxy_SetProperty: setPropertyEvent(static_cast<SetPropertyEvent*>(event)); return; case QtCollider::Event_Proxy_Destroy: destroyEvent(static_cast<DestroyEvent*>(event)); return; case QtCollider::Event_Proxy_Release: invokeScMethod(SC_SYM(prRelease)); return; default:; } } bool QObjectProxy::setParent(QObjectProxy* parentProxy) { if (qObject && parentProxy->object()) qObject->setParent(parentProxy->object()); return true; } bool QObjectProxy::setProperty(const char* property, const QVariant& val) { if (!qObject) return true; if (!qObject->setProperty(property, val)) { qcProxyDebugMsg(1, QStringLiteral("WARNING: Property '%1' not found. Setting dynamic property.").arg(property)); } return false; } bool QObjectProxy::setPropertyEvent(SetPropertyEvent* e) { return setProperty(e->property->name, e->value); } QVariant QObjectProxy::property(const char* property) { return qObject ? qObject->property(property) : QVariant(); } bool QObjectProxy::setEventHandler(int type, PyrSymbol* method, QtCollider::Synchronicity sync, bool enable) { EventHandlerData data; data.type = type; data.method = method; data.sync = sync; data.enabled = enable; EventHandlerData* d = _eventHandlers.data(); int n = _eventHandlers.size(); while (n--) { if (d->type == type) { *d = data; break; } ++d; } if (n < 0) _eventHandlers.append(data); return true; } bool QObjectProxy::setEventHandlerEnabled(int type, bool enabled) { EventHandlerData* d = _eventHandlers.data(); int n = _eventHandlers.size(); while (n--) { if (d->type == type) { d->enabled = enabled; break; } ++d; } return n >= 0; } bool QObjectProxy::connectObject(const char* signal, PyrObject* object, Qt::ConnectionType ctype) { if (!qObject) return true; QcFunctionSignalHandler* handler = new QcFunctionSignalHandler(this, signal, object, ctype); if (!handler->isValid()) { delete handler; return false; } funcSigHandlers.append(handler); return true; } bool QObjectProxy::connectMethod(const char* signal, PyrSymbol* method, Qt::ConnectionType ctype) { if (!qObject) return true; QcMethodSignalHandler* handler = new QcMethodSignalHandler(this, signal, method, ctype); if (handler->isValid()) { methodSigHandlers.append(handler); return true; } else { delete handler; return false; } } bool QObjectProxy::disconnectObject(const char* sig, PyrObject* object) { if (!qObject) return true; const QMetaObject* mo = qObject->metaObject(); QByteArray signal = QMetaObject::normalizedSignature(sig); int sigId = mo->indexOfSignal(signal); if (sigId < 0) { qcDebugMsg(1, QStringLiteral("WARNING: No such signal: '%1'").arg(signal.constData())); return false; } for (int i = 0; i < funcSigHandlers.size(); ++i) { QcFunctionSignalHandler* h = funcSigHandlers[i]; if (h->indexOfSignal() == sigId && h->function() == object) { funcSigHandlers.removeAt(i); delete h; return true; } } return false; } bool QObjectProxy::disconnectMethod(const char* sig, PyrSymbol* method) { if (!qObject) return true; const QMetaObject* mo = qObject->metaObject(); QByteArray signal = QMetaObject::normalizedSignature(sig); int sigId = mo->indexOfSignal(signal); if (sigId < 0) { qcDebugMsg(1, QStringLiteral("WARNING: No such signal: '%1'").arg(signal.constData())); return false; } for (int i = 0; i < methodSigHandlers.size(); ++i) { QcMethodSignalHandler* h = methodSigHandlers[i]; if (h->indexOfSignal() == sigId && h->method() == method) { methodSigHandlers.removeAt(i); delete h; return true; } } return false; } void QObjectProxy::destroy(DestroyAction action) { switch (action) { case DestroyObject: delete qObject; return; case DestroyProxy: delete this; return; case DestroyProxyAndObject: delete qObject; delete this; return; } } bool QObjectProxy::destroyEvent(DestroyEvent* e) { destroy(e->action()); return true; } QList<PyrObject*> QObjectProxy::children(PyrSymbol* className) { QList<PyrObject*> scChildren; if (!qObject) return scChildren; const QObjectList& children = qObject->children(); Q_FOREACH (QObject* child, children) { QObjectProxy* proxy = QObjectProxy::fromObject(child); if (!proxy) continue; PyrObject* obj = proxy->_scObject; if (obj) { if (className && !isKindOf(obj, className->u.classobj)) continue; scChildren.append(obj); } } return scChildren; } PyrObject* QObjectProxy::parent(PyrSymbol* className) { if (!qObject) return 0; QObject* parent = qObject->parent(); while (parent) { // see if this parent has a corresponding proxy QObjectProxy* proxy = QObjectProxy::fromObject(parent); if (proxy) { // if parent does not have a corresponding SC object (it is just // being deleted) return no parent; PyrObject* scobj = proxy->_scObject; if (!scobj) return 0; // if parent SC object is of desired class (or no class specified) // return it, else continue if (!className || isKindOf(scobj, className->u.classobj)) { return scobj; } } // if this parent was not appropriate continue to consider the parent's parent parent = parent->parent(); } return 0; } bool QObjectProxy::eventFilter(QObject* watched, QEvent* event) { int type = event->type(); EventHandlerData* d = _eventHandlers.data(); int n = _eventHandlers.size(); while (n--) { if (d->type == type) break; ++d; } if (n < 0) { qcProxyDebugMsg(3, QStringLiteral("No handler for event (%1), forwarding to the widget").arg(type)); return false; } QList<QVariant> args; if (!preProcessEvent(watched, event, *d, args)) { qcProxyDebugMsg(3, QStringLiteral("Event (%1, %2) not handled, forwarding to the widget") .arg(type) .arg(event->spontaneous() ? "spontaneous" : "inspontaneous")); return false; } qcProxyDebugMsg(1, QStringLiteral("Will handle event (%1, %2) -> (%3, %4)") .arg(type) .arg(event->spontaneous() ? "spontaneous" : "inspontaneous") .arg(d->method->name) .arg(d->sync == Synchronous ? "sync" : "async")); bool eventHandled = invokeEventHandler(event, *d, args); eventHandled = postProcessEvent(watched, event, eventHandled); return eventHandled; } bool QObjectProxy::invokeEventHandler(QEvent* event, EventHandlerData& eh, QList<QVariant>& args) { PyrSymbol* method = eh.method; if (eh.sync == Synchronous) { PyrSlot result; invokeScMethod(method, args, &result); if (IsTrue(&result)) { qcProxyDebugMsg(2, "Event accepted"); event->accept(); return true; } else if (IsFalse(&result)) { qcProxyDebugMsg(2, "Event ignored"); event->ignore(); return true; } } else { ScMethodCallEvent* e = new ScMethodCallEvent(method, args); QApplication::postEvent(this, e); } qcProxyDebugMsg(2, "Forwarding event to the system"); return false; } bool QObjectProxy::preProcessEvent(QObject*, QEvent* e, EventHandlerData& eh, QList<QVariant>& args) { return eh.enabled; } inline void QObjectProxy::scMethodCallEvent(ScMethodCallEvent* e) { invokeScMethod(e->method, e->args, 0, e->locked); } QObjectProxy* QObjectProxy::fromObject(QObject* object) { if (!object) return 0; const QObjectList& children = object->children(); Q_FOREACH (QObject* child, children) { ProxyToken* token = qobject_cast<QtCollider::ProxyToken*>(child); if (token) return token->proxy; } return 0; }
15,744
C++
.cpp
437
29.185355
120
0.626249
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,792
QWidgetProxy.cpp
supercollider_supercollider/QtCollider/QWidgetProxy.cpp
/************************************************************************ * * Copyright 2010-2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QWidgetProxy.h" #include "painting.h" #include "Common.h" #include "hacks/hacks_qt.hpp" #include <QApplication> #include <QLayout> #include <QMouseEvent> #include <QKeyEvent> #include <QPainter> #include <QFontMetrics> #include <QUrl> #include <QMimeData> #include <QDrag> #ifdef Q_WS_X11 # include "hacks/hacks_x11.hpp" # include <QX11Info> # include <X11/Xlib.h> // X11 defines the following, clashing with QEvent::Type enum # undef KeyPress # undef KeyRelease #endif #ifdef Q_OS_MAC # include "./hacks/hacks_mac.hpp" #endif using namespace QtCollider; QAtomicInt QWidgetProxy::_globalEventMask = 0; QMimeData* QWidgetProxy::sDragData = 0; QString QWidgetProxy::sDragLabel; QWidgetProxy::QWidgetProxy(QWidget* w, PyrObject* po): QObjectProxy(w, po), _keyEventWidget(w), _mouseEventWidget(w), _performDrag(false) {} void QWidgetProxy::setKeyEventWidget(QWidget* w) { if (w == 0 || w == _keyEventWidget) return; QWidget* me = widget(); if (_keyEventWidget != me) _keyEventWidget->removeEventFilter(this); _keyEventWidget = w; if (_keyEventWidget != me) { _keyEventWidget->installEventFilter(this); } } void QWidgetProxy::setMouseEventWidget(QWidget* w) { if (w == 0 || w == _mouseEventWidget) return; QWidget* me = widget(); if (_mouseEventWidget != me) _mouseEventWidget->removeEventFilter(this); _mouseEventWidget = w; if (_mouseEventWidget != me) { _mouseEventWidget->installEventFilter(this); } } bool QWidgetProxy::alwaysOnTop() { QWidget* w = widget(); if (!w) return false; Qt::WindowFlags flags = w->windowFlags(); if (flags & Qt::Window && flags & Qt::WindowStaysOnTopHint) return true; else return false; } void QWidgetProxy::refresh() { QWidget* w = widget(); if (w) sendRefreshEventRecursive(w); } void QWidgetProxy::setLayout(QObjectProxy* layoutProxy) { QWidget* w = widget(); QLayout* l = qobject_cast<QLayout*>(layoutProxy->object()); if (!w || !l) return; QLayout* exLayout = w->layout(); if (exLayout != l) { if (exLayout != 0) { qcDebugMsg(2, QStringLiteral("Deleting old layout.")); delete exLayout; } qcDebugMsg(2, QStringLiteral("Setting layout.")); w->setLayout(l); l->activate(); } else { qcDebugMsg(2, QStringLiteral("Layout same as existing. Will do nothing.")); } } bool QWidgetProxy::setParent(QObjectProxy* parentProxy) { QObject* parent = parentProxy->object(); if (!parent || !widget()) return true; if (parent->isWidgetType()) { QWidget* pw = qobject_cast<QWidget*>(parent); bool ok = pw->metaObject()->invokeMethod(pw, "addChild", Q_ARG(QWidget*, widget())); if (!ok) widget()->setParent(pw); return true; } return false; } void QWidgetProxy::setDragData(QMimeData* data, const QString& label) { if (data == 0) return; if (sDragData == 0) { sDragData = data; sDragLabel = label; _performDrag = true; } else { delete data; qcErrorMsg("QWidgetProxy: attempt at starting a drag while another one is in progress."); } } void QWidgetProxy::customEvent(QEvent* e) { int type = e->type(); switch (type) { case QtCollider::Event_Proxy_BringFront: bringFrontEvent(); return; case QtCollider::Event_Proxy_SetFocus: setFocusEvent(static_cast<SetFocusEvent*>(e)); return; case QtCollider::Event_Proxy_SetAlwaysOnTop: setAlwaysOnTopEvent(static_cast<SetAlwaysOnTopEvent*>(e)); return; default: QObjectProxy::customEvent(e); } } void QWidgetProxy::bringFrontEvent() { QWidget* w = widget(); if (!w) return; w->setWindowState(w->windowState() & ~Qt::WindowMinimized | Qt::WindowActive); w->show(); w->raise(); #ifdef Q_WS_X11 raise_window(QX11Info::display(), w); #endif #ifdef Q_OS_MAC QtCollider::Mac::activateApp(); #endif } void QWidgetProxy::setFocusEvent(QtCollider::SetFocusEvent* e) { if (!widget()) return; if (e->focus) widget()->setFocus(Qt::OtherFocusReason); else widget()->clearFocus(); } void QWidgetProxy::setAlwaysOnTopEvent(QtCollider::SetAlwaysOnTopEvent* e) { QWidget* w = widget(); if (!w) return; Qt::WindowFlags flags = w->windowFlags(); if (flags & Qt::Window) { if (e->alwaysOnTop) flags |= Qt::WindowStaysOnTopHint; else flags &= ~Qt::WindowStaysOnTopHint; // record the initial state to restore it later QPoint pos = w->pos(); bool visible = w->isVisible(); w->setWindowFlags(flags); // setting window flags will move the window to (0,0) and hide it, // so restore the initial state w->move(pos); if (visible) w->show(); } } void QWidgetProxy::performDrag() { Q_ASSERT(sDragData); QFont f; const QString& label = sDragLabel; QFontMetrics fm(f); QSize size = fm.size(0, label) + QSize(8, 4); QPixmap pix(size); QPainter p(&pix); p.setBrush(QColor(255, 255, 255)); QRect r(pix.rect()); p.drawRect(r.adjusted(0, 0, -1, -1)); p.drawText(r, Qt::AlignCenter, label); p.end(); QDrag* drag = new QDrag(widget()); drag->setMimeData(sDragData); drag->setPixmap(pix); drag->setHotSpot(QPoint(0, +r.height() + 2)); drag->exec(); sDragData = 0; sDragLabel.clear(); } bool QWidgetProxy::preProcessEvent(QObject* o, QEvent* e, EventHandlerData& eh, QList<QVariant>& args) { // NOTE We assume that qObject need not be checked here, as we wouldn't get events if // it wasn't existing int acquired_globalEventMask = _globalEventMask.loadRelaxed(); switch (eh.type) { case QEvent::KeyPress: return ((acquired_globalEventMask & KeyPress) || eh.enabled) && interpretKeyEvent(o, e, args); case QEvent::KeyRelease: return ((acquired_globalEventMask & KeyRelease) || eh.enabled) && interpretKeyEvent(o, e, args); case QEvent::MouseButtonPress: case QEvent::MouseMove: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::Enter: case QEvent::Leave: return eh.enabled && interpretMouseEvent(o, e, args); case QEvent::Wheel: return eh.enabled && interpretMouseWheelEvent(o, e, args); case QEvent::DragEnter: case QEvent::DragMove: case QEvent::Drop: return eh.enabled && interpretDragEvent(o, e, args); default: return eh.enabled; } } bool QWidgetProxy::interpretMouseEvent(QObject* o, QEvent* e, QList<QVariant>& args) { if (o != _mouseEventWidget || !_mouseEventWidget->isEnabled()) return false; QWidget* w = widget(); QEvent::Type etype = e->type(); if (etype == QEvent::Enter || etype == QEvent::Leave) return true; QMouseEvent* mouse = static_cast<QMouseEvent*>(e); QPoint pt = (_mouseEventWidget == w ? mouse->pos() : _mouseEventWidget->mapTo(w, mouse->pos())); args << pt.x(); args << pt.y(); args << (int)mouse->modifiers(); if (etype == QEvent::MouseMove) { int buttons = mouse->buttons(); if (buttons == 0) { // Special treatment of mouse-tracking events. QWidget* win = w->window(); // Only accept if window has a special property enabled. if (!(win && win->property("_qc_win_mouse_tracking").toBool())) return false; // Reject the events when mouse pointer leaves the window, // resulting in out-of-bounds coordinates if (win == w) { if (pt.x() < 0 || pt.x() >= w->width() || pt.y() < 0 || pt.y() >= w->height()) return false; } } args << (int)mouse->buttons(); } else { // MouseButtonPress, MouseButtonDblClick, MouseButtonRelease int button; switch (mouse->button()) { case Qt::LeftButton: button = 0; break; case Qt::RightButton: button = 1; break; case Qt::MiddleButton: button = 2; break; default: button = -1; } args << button; if (etype == QEvent::MouseButtonPress) args << 1; else if (etype == QEvent::MouseButtonDblClick) args << 2; } return true; } bool QWidgetProxy::interpretMouseWheelEvent(QObject* o, QEvent* e, QList<QVariant>& args) { // NOTE: There seems to be a bug in wheel event propagation: // the event is propagated to parent twice! // Therefore we do not let the propagated events through to SC, // (we only let the "spontaneous" ones). if (o != _mouseEventWidget || !e->spontaneous() || !_mouseEventWidget->isEnabled()) return false; QWheelEvent* we = static_cast<QWheelEvent*>(e); QWidget* w = widget(); QPointF pt = _mouseEventWidget == w ? we->position() : _mouseEventWidget->mapTo(w, we->position().toPoint()); // only hi-res trackpads return pixelDelta everything else uses angleDelta.. QPointF delta = we->pixelDelta().isNull() ? we->angleDelta() / 8.f // scaled to return steps of 15 : we->pixelDelta() * 0.25f; // this matches old scaling of delta args << pt.x(); args << pt.y(); args << (int)we->modifiers(); args << delta.x(); args << delta.y(); return true; } bool QWidgetProxy::interpretKeyEvent(QObject* o, QEvent* e, QList<QVariant>& args) { if (o != _keyEventWidget || !_keyEventWidget->isEnabled()) return false; QKeyEvent* ke = static_cast<QKeyEvent*>(e); int key = ke->key(); int mods = ke->modifiers(); QChar character; #ifdef Q_OS_MAC bool isLetter = key >= Qt::Key_A && key <= Qt::Key_Z; if (mods & Qt::MetaModifier && isLetter) { character = QChar(key - Qt::Key_A + 1); } else if (mods & Qt::AltModifier && isLetter) { character = (mods & Qt::ShiftModifier) ? QChar(key) : QChar(key - Qt::Key_A + 97); } else #endif { QString text(ke->text()); if (text.count()) character = text[0]; } int unicode = character.unicode(); #ifdef Q_WS_X11 KeySym sym = ke->nativeVirtualKey(); int keycode = XKeysymToKeycode(QX11Info::display(), sym); #else // FIXME: On Mac OS X, this does not work for modifier keys int keycode = ke->nativeVirtualKey(); #endif args << character; args << mods; args << unicode; args << keycode; args << key; args << ke->spontaneous(); return true; } static QString urlAsString(const QUrl& url) { if (QURL_IS_LOCAL_FILE(url)) return url.toLocalFile(); else return url.toString(); } static bool interpretMimeData(const QMimeData* data, QList<QVariant>& args) { if (data->hasUrls()) { QList<QUrl> urls = data->urls(); if (urls.count() > 1) { QVariantList list; Q_FOREACH (QUrl url, urls) list << urlAsString(url); args << QVariant(list); } else { args << urlAsString(urls[0]); } } else if (data->hasText()) { args << data->text(); } else { return false; } return true; } bool QWidgetProxy::interpretDragEvent(QObject* o, QEvent* e, QList<QVariant>& args) { if (o != _mouseEventWidget) return false; QDropEvent* dnd = static_cast<QDropEvent*>(e); const QMimeData* data = dnd->mimeData(); if (dnd->type() == QEvent::DragEnter) { bool internal = data->hasFormat("application/supercollider"); args << internal; if (!internal) interpretMimeData(data, args); } else { QPoint pos = dnd->pos(); args << pos.x() << pos.y(); } return true; } bool QWidgetProxy::postProcessEvent(QObject* object, QEvent* event, bool handled) { if (_performDrag) { _performDrag = false; performDrag(); return true; } return handled; } void QWidgetProxy::customPaint(QPainter* painter) { if (QtCollider::paintingAnnounced()) { qcDebugMsg(1, "WARNING: Custom painting already in progress. Will not paint."); return; } QtCollider::announcePainting(); QtCollider::lockLang(); if (QtCollider::beginPainting(painter, this)) { invokeScMethod(SC_SYM(doDrawFunc), QList<QVariant>(), 0, true); QtCollider::endPainting(); } QtCollider::unlockLang(); } void QWidgetProxy::sendRefreshEventRecursive(QWidget* w) { QEvent event(static_cast<QEvent::Type>(QtCollider::Event_Refresh)); QApplication::sendEvent(w, &event); const QObjectList& children = w->children(); Q_FOREACH (QObject* child, children) { if (child->isWidgetType()) sendRefreshEventRecursive(static_cast<QWidget*>(child)); } }
14,103
C++
.cpp
417
27.738609
113
0.620362
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,793
factories.cpp
supercollider_supercollider/QtCollider/factories.cpp
/************************************************************************ * * Copyright 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcObjectFactory.h" #include "QcWidgetFactory.h" #include <QLabel> QC_DECLARE_QWIDGET_FACTORY(QLabel); #ifdef SC_USE_QTWEBENGINE # include "widgets/QcWebView.h" QC_DECLARE_QWIDGET_FACTORY(WebView); #endif static void doLoadFactories() { QC_ADD_FACTORY(QcDefaultWidget); QC_ADD_FACTORY(QcHLayoutWidget); QC_ADD_FACTORY(QcVLayoutWidget); QC_ADD_FACTORY(QLabel); QC_ADD_FACTORY(QcTextField); QC_ADD_FACTORY(QcCheckBox); QC_ADD_FACTORY(QcListWidget); QC_ADD_FACTORY(QcPopUpMenu); QC_ADD_FACTORY(QcButton); QC_ADD_FACTORY(QcCustomPainted); QC_ADD_FACTORY(QcFileDialog); QC_ADD_FACTORY(QcGraph); QC_ADD_FACTORY(QcKnob); QC_ADD_FACTORY(QcLevelIndicator); QC_ADD_FACTORY(QcMultiSlider); QC_ADD_FACTORY(QcNumberBox); QC_ADD_FACTORY(QcPenPrinter); QC_ADD_FACTORY(QcRangeSlider); QC_ADD_FACTORY(QcScope); QC_ADD_FACTORY(QcScopeShm); QC_ADD_FACTORY(QcScrollWidget); QC_ADD_FACTORY(QcScrollArea); QC_ADD_FACTORY(QcSlider); QC_ADD_FACTORY(QcSlider2D); QC_ADD_FACTORY(QcWaveform); QC_ADD_FACTORY(QcTextEdit); QC_ADD_FACTORY(QcTreeWidget); QC_ADD_FACTORY(QcMenu); QC_ADD_FACTORY(QcToolBar); QC_ADD_FACTORY(QcAction); QC_ADD_FACTORY(QcWidgetAction); QC_ADD_FACTORY(QcCallback); QC_ADD_FACTORY(QcWindow); QC_ADD_FACTORY(QcScrollWindow); QC_ADD_FACTORY(QcHBoxLayout); QC_ADD_FACTORY(QcVBoxLayout); QC_ADD_FACTORY(QcGridLayout); QC_ADD_FACTORY(QcStackLayout); QC_ADD_FACTORY(QtDownload); #ifdef SC_USE_QTWEBENGINE QC_ADD_FACTORY(WebView); #endif #if defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QC_ADD_FACTORY(QcQuartzComposerView); #endif } namespace QtCollider { void loadFactories() { doLoadFactories(); } } // namespace QtCollider
2,724
C++
.cpp
78
31.474359
74
0.698635
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,794
QtDownload.cpp
supercollider_supercollider/QtCollider/QtDownload.cpp
/* * QtDownload.cpp * * * Copyright 2013 Scott Wilson. * * This file is part of SuperCollider. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "Common.h" #include "QtDownload.h" #include "QcWidgetFactory.h" #include <QCoreApplication> #include <QUrl> #include <QNetworkRequest> #include <QFile> #include <QDebug> QC_DECLARE_QOBJECT_FACTORY(QtDownload); QtDownload::QtDownload(): QObject(0), started(false) {} QtDownload::~QtDownload() {} void QtDownload::setSource(const QString& t) { m_target = t; } void QtDownload::setDestination(const QString& l) { m_local = l; } void QtDownload::downloadFinished() { if (m_reply->error() == QNetworkReply::NoError) { // only write if no error QFile localFile(this->m_local); if (!localFile.open(QIODevice::WriteOnly)) return; const QByteArray sdata = m_reply->readAll(); localFile.write(sdata); qDebug() << sdata; localFile.close(); // call action Q_EMIT(doFinished()); } m_reply->deleteLater(); m_manager->deleteLater(); } void QtDownload::download() { if (!started) { started = true; m_manager = new QNetworkAccessManager(this); QUrl url = QUrl::fromEncoded(this->m_target.toLocal8Bit()); QNetworkRequest request; request.setUrl(url); m_reply = m_manager->get(request); QObject::connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64))); QObject::connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError))); bool fin = QObject::connect(m_reply, SIGNAL(finished()), this, SLOT(downloadFinished())); if (!fin) { qWarning("Download could not connect"); } } } void QtDownload::cancel() { if (m_reply) { m_reply->disconnect(); m_reply->abort(); } } void QtDownload::replyError(QNetworkReply::NetworkError errorCode) { qWarning() << m_reply->errorString(); // call action Q_EMIT(doError()); } void QtDownload::downloadProgress(qint64 received, qint64 total) { qDebug() << received << total; // call action Q_EMIT(doProgress(static_cast<int>(received), static_cast<int>(total))); }
2,954
C++
.cpp
84
30.178571
97
0.675193
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,795
debug.cpp
supercollider_supercollider/QtCollider/debug.cpp
/************************************************************************ * * Copyright 2010-2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "debug.h" #include <QAtomicInt> static QAtomicInt& debugLevelInt() { static QAtomicInt* i = new QAtomicInt(0); return *i; } int QtCollider::debugLevel() { int l = debugLevelInt().loadRelaxed(); return l; } void QtCollider::setDebugLevel(int i) { debugLevelInt() = i; }
1,211
C++
.cpp
31
36.774194
74
0.651064
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,796
QcObjectFactory.cpp
supercollider_supercollider/QtCollider/QcObjectFactory.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcObjectFactory.h" namespace QtCollider { QcFactoryHash& factories() { static QcFactoryHash* factoryHash = new QcFactoryHash(); return *factoryHash; } }
1,088
C++
.cpp
27
38.111111
74
0.655303
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,797
prim_QWidget.cpp
supercollider_supercollider/QtCollider/primitives/prim_QWidget.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "../type_codec.hpp" #include "../QWidgetProxy.h" #include "../Common.h" #include <PyrKernel.h> #include <SCBase.h> #include <QWidget> #include <QThread> #include <QApplication> #include <QDrag> #include <QMimeData> // WARNING these primitives have to always execute asynchronously, or Cocoa language client will // hang. #define QWIDGET_PROXY_RECEIVER(slot) qobject_cast<QWidgetProxy*>(QtCollider::read<QObjectProxy*>(slot)) namespace QtCollider { QC_LANG_PRIMITIVE(QWidget_SetFocus, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); QApplication::postEvent(proxy, new SetFocusEvent(IsTrue(a))); return errNone; } QC_LANG_PRIMITIVE(QWidget_BringFront, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); QApplication::postEvent(proxy, new QEvent((QEvent::Type)QtCollider::Event_Proxy_BringFront)); return errNone; } QC_LANG_PRIMITIVE(QWidget_Refresh, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); proxy->refresh(); return errNone; } QC_LANG_PRIMITIVE(QWidget_MapToGlobal, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QWidget* w = proxy->widget(); if (!w) return errNone; QPoint pt(QtCollider::get(a)); pt = w->mapToGlobal(pt); QtCollider::set(r, pt); return errNone; } QC_LANG_PRIMITIVE(QWidget_SetLayout, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!isKindOfSlot(a, SC_CLASS(Layout))) return errWrongType; QWidgetProxy* wProxy = QWIDGET_PROXY_RECEIVER(r); if (!wProxy->compareThread()) return QtCollider::wrongThreadError(); QObjectProxy* lProxy = QtCollider::get<QObjectProxy*>(a); wProxy->setLayout(lProxy); return errNone; } QC_LANG_PRIMITIVE(QWidget_GetAlwaysOnTop, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* wProxy = QWIDGET_PROXY_RECEIVER(r); if (QThread::currentThread() != wProxy->thread()) return errFailed; SetBool(r, wProxy->alwaysOnTop()); return errNone; } QC_LANG_PRIMITIVE(QWidget_SetAlwaysOnTop, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* wProxy = QWIDGET_PROXY_RECEIVER(r); QApplication::postEvent(wProxy, new SetAlwaysOnTopEvent(IsTrue(a))); return errNone; } struct MimeData : public QMimeData { virtual ~MimeData() { qcDebugMsg(1, "Drag data object destroyed, clearing QView.currentDrag."); QtCollider::lockLang(); PyrClass* classView = getsym("View")->u.classobj; PyrSymbol* symClearDrag = getsym("prClearCurrentDrag"); if (!classView || !symClearDrag) return; QtCollider::runLang(classView, symClearDrag); QtCollider::unlockLang(); } }; QC_LANG_PRIMITIVE(QWidget_StartDrag, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { qcDebugMsg(1, "Starting drag..."); QWidgetProxy* wProxy = QWIDGET_PROXY_RECEIVER(r); if (!wProxy->compareThread()) return QtCollider::wrongThreadError(); PyrSlot* data = a + 1; QString str = QtCollider::get(a + 2); QString label = QtCollider::get(a); QMimeData* mime = new QtCollider::MimeData; mime->setData("application/supercollider", QByteArray()); QColor color = QtCollider::get(data); if (color.isValid()) mime->setColorData(QVariant(color)); if (!str.isEmpty()) mime->setText(str); wProxy->setDragData(mime, label); return errNone; } QC_LANG_PRIMITIVE(QWidget_SetGlobalEventEnabled, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotInt(a + 0)) return errWrongType; int event = QtCollider::get(a + 0); bool enabled = IsTrue(a + 1); if (!enabled && !IsFalse(a + 1)) return errWrongType; QWidgetProxy::setGlobalEventEnabled((QWidgetProxy::GlobalEvent)event, enabled); return errNone; } QC_LANG_PRIMITIVE(QWidget_SetAcceptsMouse, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QWidget* w = proxy->widget(); if (!w) return errNone; bool accept = IsTrue(a); w->setAttribute(Qt::WA_TransparentForMouseEvents, !accept); return errNone; } QC_LANG_PRIMITIVE(QWidget_AcceptsMouse, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QWidgetProxy* proxy = QWIDGET_PROXY_RECEIVER(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QWidget* w = proxy->widget(); if (!w) return errNone; bool accept = !w->testAttribute(Qt::WA_TransparentForMouseEvents); SetBool(r, accept); return errNone; } void defineQWidgetPrimitives() { LangPrimitiveDefiner definer; definer.define<QWidget_SetFocus>(); definer.define<QWidget_BringFront>(); definer.define<QWidget_Refresh>(); definer.define<QWidget_MapToGlobal>(); definer.define<QWidget_SetLayout>(); definer.define<QWidget_GetAlwaysOnTop>(); definer.define<QWidget_SetAlwaysOnTop>(); definer.define<QWidget_StartDrag>(); definer.define<QWidget_SetGlobalEventEnabled>(); definer.define<QWidget_AcceptsMouse>(); definer.define<QWidget_SetAcceptsMouse>(); } } // namespace QtCollider
6,425
C++
.cpp
163
34.871166
103
0.689989
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,798
prim_misc.cpp
supercollider_supercollider/QtCollider/primitives/prim_misc.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "../Common.h" #include "../type_codec.hpp" #include "../QcApplication.h" #include "../QObjectProxy.h" #include "../style/style.hpp" #include "../QcCallback.hpp" #include "QtCollider.h" #ifdef Q_OS_MAC # include "../hacks/hacks_mac.hpp" #endif #include <PyrKernel.h> #include <QDesktopServices> #include <QFontDatabase> #include <QFontInfo> #include <QFontMetrics> #include <QStyleFactory> #include <QCursor> #include <QScreen> namespace QtCollider { QC_LANG_PRIMITIVE(QtGUI_SetDebugLevel, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QtCollider::setDebugLevel(QtCollider::get(a)); return errNone; } QC_LANG_PRIMITIVE(QtGUI_DebugLevel, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { SetInt(r, QtCollider::debugLevel()); return errNone; } QC_LANG_PRIMITIVE(QWindow_ScreenBounds, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QRect screenGeometry = QApplication::primaryScreen()->geometry(); QtCollider::set(r, screenGeometry); return errNone; } QC_LANG_PRIMITIVE(QWindow_AvailableGeometry, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QRect rect = QApplication::primaryScreen()->availableGeometry(); QtCollider::set(r, rect); return errNone; } QC_LANG_PRIMITIVE(Qt_StringBounds, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QString str = QtCollider::get(a); QFont f = QtCollider::get(a + 1); QFontMetrics fm(f); QRect bounds = fm.boundingRect(str); // we keep the font height even on empty string; if (str.isEmpty()) bounds.setHeight(fm.height()); QtCollider::set(r, bounds); return errNone; } QC_LANG_PRIMITIVE(Qt_AvailableFonts, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QVariantList list; #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QFontDatabase database; auto families = database.families(); #else auto families = QFontDatabase::families(); #endif Q_FOREACH (QString family, families) list << family; QtCollider::set(r, list); return errNone; } QC_LANG_PRIMITIVE(QFont_SetDefaultFont, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (!isKindOfSlot(a + 0, SC_CLASS(Font))) return errWrongType; QFont font(QtCollider::read<QFont>(a + 0)); const char* className = IsSym(a + 1) ? slotRawSymbol(a + 1)->name : 0; QApplication::setFont(font, className); return errNone; } QC_LANG_PRIMITIVE(QFont_DefaultFamilyForStyle, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { // NOTE: // On X11 systems we rely on default fontconfig mappings of font familiy names, // as style hints are not necessarily supported. // On other systems, style hints should work. if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (!IsInt(a)) return errWrongType; QFont::StyleHint styleHint; QString family; switch (slotRawInt(a)) { case 0: styleHint = QFont::SansSerif; family = "sans-serif"; break; case 1: styleHint = QFont::Serif; family = "serif"; break; case 2: styleHint = QFont::Monospace; family = "monospace"; break; default: styleHint = QFont::AnyStyle; } QFont font(family); font.setStyleHint(styleHint, QFont::PreferMatch); QtCollider::set(r, font.defaultFamily()); return errNone; } QC_LANG_PRIMITIVE(Qt_GlobalPalette, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QPalette p(QApplication::palette()); QtCollider::set(r, p); return errNone; } QC_LANG_PRIMITIVE(Qt_SetGlobalPalette, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); // The line below is a workaround. The non-win term causes Error C2440 in VS // https://msdn.microsoft.com/en-us/library/sy5tsf8z.aspx #if defined(_MSC_VER) QPalette p = (QPalette &&) QtCollider::get(a); #else QPalette p = QtCollider::get(a); #endif QApplication::setPalette(p); return errNone; } QC_LANG_PRIMITIVE(Qt_FocusWidget, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QWidget* w = QApplication::focusWidget(); #ifdef Q_OS_MAC // On Mac we need to make additional checks, as Qt does not monitor // focus changes to native Cocoa windows in the same application. if (w && !QtCollider::Mac::isKeyWindow(w)) w = 0; #endif if (w) { QObjectProxy* proxy = QObjectProxy::fromObject(w); if (proxy && proxy->scObject()) { SetObject(r, proxy->scObject()); return errNone; } } SetNil(r); return errNone; } QC_LANG_PRIMITIVE(Qt_SetStyle, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QString str = QtCollider::get(a); if (str.isEmpty()) return errFailed; QStyle* style = QStyleFactory::create(str); if (!style) return errFailed; QApplication::setStyle(new QtCollider::Style::StyleImpl(style)); return errNone; } QC_LANG_PRIMITIVE(Qt_AvailableStyles, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QVariantList list; Q_FOREACH (QString key, QStyleFactory::keys()) list << key; QtCollider::set(r, list); return errNone; } QC_LANG_PRIMITIVE(QWebView_ClearMemoryCaches, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); // @TODO WebEngine: New cache method? // QWebEngineSettings::clearMemoryCaches(); return errNone; } QC_LANG_PRIMITIVE(Qt_IsMethodOverridden, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotObj(a) || NotSym(a + 1)) return errWrongType; PyrObject* self = slotRawObject(r); PyrObjectHdr* superclass = slotRawObject(a); PyrSymbol* method = slotRawSymbol(a + 1); for (PyrClass* klass = self->classptr; klass != superclass && klass != class_object; klass = slotRawSymbol(&klass->superclass)->u.classobj) { PyrSlot* methodSlot = &klass->methods; if (!IsObj(methodSlot)) continue; PyrObject* methodArray = slotRawObject(methodSlot); PyrSlot* methods = methodArray->slots; for (int i = 0; i < methodArray->size; ++i) { PyrMethod* m = slotRawMethod(methods + i); if (slotRawSymbol(&m->name) == method) { SetTrue(r); return errNone; } } } SetFalse(r); return errNone; } QC_LANG_PRIMITIVE(Qt_CursorPosition, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QtCollider::set(r, QCursor::pos()); return errNone; } QC_LANG_PRIMITIVE(Qt_SetUrlHandler, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QString str = QtCollider::get(a); if (IsNil(a + 1)) { QDesktopServices::unsetUrlHandler(str); } else { QcCallback* cb = QtCollider::get(a + 1); QDesktopServices::setUrlHandler(str, cb, "onCalled"); } return errNone; } QC_LANG_PRIMITIVE(Qt_SetAppMenus, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QList<QMenu*> menuList; if (isKindOfSlot(a, class_array)) { QMenuBar* menuBar = QcApplication::getMainMenu(); if (menuBar) { menuBar->clear(); PyrObject* obj = slotRawObject(a); PyrSlot* slots = obj->slots; int size = obj->size; for (int i = 0; i < size; ++i, ++slots) { QMenu* menu = QtCollider::get<QMenu*>(slots); if (menu) { menuBar->addMenu(menu); } else { menuBar->addSeparator(); } } } } return errNone; } QC_LANG_PRIMITIVE(QView_AddActionToView, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QObjectProxy* widgetObj = TypeCodec<QObjectProxy*>::safeRead(a); QObjectProxy* actionObj = TypeCodec<QObjectProxy*>::safeRead(a + 1); QObjectProxy* beforeObj = TypeCodec<QObjectProxy*>::safeRead(a + 2); if (widgetObj && actionObj) { QWidget* widget = qobject_cast<QWidget*>(widgetObj->object()); QAction* action = qobject_cast<QAction*>(actionObj->object()); QAction* beforeAction = beforeObj ? qobject_cast<QAction*>(beforeObj->object()) : 0; if (!beforeAction) { PyrSlot* indexArg = a + 2; if (NotNil(indexArg)) { if (IsInt(indexArg)) { int index = std::max(slotRawInt(indexArg), 0); auto actions = widget->actions(); if (index < actions.size()) { beforeAction = actions[index]; } } else { return errFailed; } } } if (widget && action) { if (beforeAction) { widget->insertAction(beforeAction, action); } else { widget->addAction(action); } return errNone; } } return errFailed; } QC_LANG_PRIMITIVE(QView_RemoveActionFromView, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QObjectProxy* widgetObj = TypeCodec<QObjectProxy*>::safeRead(a); QObjectProxy* actionObj = TypeCodec<QObjectProxy*>::safeRead(a + 1); if (widgetObj && actionObj) { QWidget* widget = qobject_cast<QWidget*>(widgetObj->object()); QAction* action = qobject_cast<QAction*>(actionObj->object()); if (widget && action) { widget->removeAction(action); return errNone; } } return errFailed; } QC_LANG_PRIMITIVE(QView_RemoveAllActionsFromView, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QObjectProxy* widgetObj = TypeCodec<QObjectProxy*>::safeRead(a); if (widgetObj) { QWidget* widget = qobject_cast<QWidget*>(widgetObj->object()); if (widget) { auto actions = widget->actions(); for (auto action : actions) { widget->removeAction(action); } return errNone; } } return errFailed; } void defineMiscPrimitives() { LangPrimitiveDefiner definer; definer.define<QtGUI_SetDebugLevel>(); definer.define<QtGUI_DebugLevel>(); definer.define<QWindow_ScreenBounds>(); definer.define<QWindow_AvailableGeometry>(); definer.define<Qt_StringBounds>(); definer.define<Qt_AvailableFonts>(); definer.define<QFont_SetDefaultFont>(); definer.define<QFont_DefaultFamilyForStyle>(); definer.define<Qt_GlobalPalette>(); definer.define<Qt_SetGlobalPalette>(); definer.define<Qt_FocusWidget>(); definer.define<Qt_SetStyle>(); definer.define<Qt_AvailableStyles>(); definer.define<Qt_IsMethodOverridden>(); definer.define<QWebView_ClearMemoryCaches>(); definer.define<Qt_CursorPosition>(); definer.define<Qt_SetUrlHandler>(); definer.define<Qt_SetAppMenus>(); definer.define<QView_AddActionToView>(); definer.define<QView_RemoveActionFromView>(); definer.define<QView_RemoveAllActionsFromView>(); } } // namespace QtCollider
13,078
C++
.cpp
352
30.823864
92
0.64548
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,799
prim_QImage.cpp
supercollider_supercollider/QtCollider/primitives/prim_QImage.cpp
/************************************************************************ * * This file is part of SuperCollider Qt GUI. * * Copyright 2013 Jakob Leben (jakob.leben@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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "image_primitive_helper_funcs.h" #include "../image.h" #include "../QcApplication.h" #include "../Common.h" #include "../type_codec.hpp" #include "../painting.h" #include "../hacks/hacks_qt.hpp" #include <PyrKernel.h> #include <GC.h> #include <QImage> #include <QUrl> #include <QPainter> #include <QtSvg/QSvgRenderer> #include <QImageReader> #include <QImageWriter> #include <QEventLoop> #include <QTimer> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <cassert> namespace QC = QtCollider; namespace QtCollider { QPainter* imgPainter = 0; QC_LANG_PRIMITIVE(QImage_NewPath, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QString path(QtCollider::get<QString>(a)); QPixmap pixmap(path); if (pixmap.isNull()) return errFailed; Image* image = new Image(); image->setPixmap(pixmap); initialize_image_object(g, slotRawObject(r), image); return errNone; } QC_LANG_PRIMITIVE(QImage_NewSVG, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QString path(QtCollider::get<QString>(a)); QSize size(QtCollider::get<QSize>(a + 1)); QString element(QtCollider::get<QString>(a + 2)); QPainter painter; QSvgRenderer svgRenderer(path); if (size.isEmpty() || size.isNull()) { size = svgRenderer.defaultSize(); } QPixmap pixmap(size); pixmap.fill(Qt::transparent); painter.begin(&pixmap); if (element.isEmpty()) { svgRenderer.render(&painter); } else { svgRenderer.render(&painter, element); } painter.end(); Image* image = new Image(); image->setPixmap(pixmap); initialize_image_object(g, slotRawObject(r), image); return errNone; } QC_LANG_PRIMITIVE(QImage_NewURL, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { // FIXME: // We can not run an event loop while waiting to receive data, because that // would allow GUI to try and call into the language, resulting in a deadlock. qcErrorMsg("QImage: loading from URL not yet implemented."); return errFailed; #if 0 QString url_str = QtCollider::get(a); QUrl url(url_str); if( !url.isValid() || url.isEmpty() ) { qcErrorMsg( QStringLiteral("QImage: invalid or empty URL: ") + url_str ); return errFailed; } if( QURL_IS_LOCAL_FILE(url) ) { if( QImage_InitPath( g, slotRawObject(r), url.toLocalFile() ) ) { return errNone; } else { qcErrorMsg( QStringLiteral("QImage: file doesn't exist or can't be opened: ") + url_str ); return errFailed; } } if( !IsFloat(a+1) && !IsInt(a+1) ) return errWrongType; // Take a safe read to allow Integers: float timeout = QtCollider::get(a+1); QNetworkAccessManager manager; QScopedPointer<QNetworkReply> reply( manager.get( QNetworkRequest(url) ) ); QEventLoop loop; QcApplication::connect( &manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()) ); QcApplication::connect( reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()) ); QTimer::singleShot( 100 * timeout, &loop, SLOT(quit()) ); loop.exec(); // blocks if( reply->error() != QNetworkReply::NoError ) { qcErrorMsg( QStringLiteral("QImage: error trying to download: ") + url_str ); return errFailed; } else if( !reply->isFinished() ) { qcErrorMsg( QStringLiteral("QImage: timeout while trying to download: ") + url_str ); reply->abort(); return errFailed; } QByteArray byteArray = reply->readAll(); if( byteArray.isEmpty() ) { qcErrorMsg( QStringLiteral("QImage: no data received: ") + url_str ); return errFailed; } if( QImage_InitFromData( g, slotRawObject(r), byteArray ) ) { return errNone; } else { qcErrorMsg( QStringLiteral("QImage: failed trying to open downloaded data: ") + url_str ); return errFailed; } #endif } QC_LANG_PRIMITIVE(QImage_NewEmpty, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a) || NotInt(a + 1)) return errWrongType; int width = QtCollider::read<int>(a); int height = QtCollider::read<int>(a + 1); QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied); qimage.fill(QColor(Qt::transparent).rgba()); Image* image = new Image; image->setImage(qimage); initialize_image_object(g, slotRawObject(r), image); return errNone; } QC_LANG_PRIMITIVE(QImage_NewFromWindow, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QObjectProxy* proxy = QtCollider::get(a); if (!proxy) return errWrongType; QWidget* widget = qobject_cast<QWidget*>(proxy->object()); if (!widget) return errWrongType; QRect rect; if (IsObj(a + 1) && slotRawObject(a + 1)->classptr == SC_CLASS(Rect)) rect = QtCollider::read<QRect>(a + 1); else if (NotNil(a + 1)) return errWrongType; QPixmap pixmap = widget->grab(rect); if (pixmap.isNull()) return errFailed; Image* image = new Image; image->setPixmap(pixmap); initialize_image_object(g, slotRawObject(r), image); return errNone; } QC_LANG_PRIMITIVE(QImage_Free, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); if (image->isPainting()) { qcErrorMsg("QImage: can not free while being painted."); return errFailed; } image->clear(); return errNone; } QC_LANG_PRIMITIVE(QImage_HasSmoothTransformation, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); QC::write<bool>(r, image->transformationMode == Qt::SmoothTransformation); return errNone; } QC_LANG_PRIMITIVE(QImage_SetSmoothTransformation, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); bool smooth = QC::get(a); Image* image = to_image(r); image->transformationMode = smooth ? Qt::SmoothTransformation : Qt::FastTransformation; return errNone; } QC_LANG_PRIMITIVE(QImage_Width, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); SetInt(r, image->width()); return errNone; } QC_LANG_PRIMITIVE(QImage_Height, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); SetInt(r, image->height()); return errNone; } QC_LANG_PRIMITIVE(QImage_SetSize, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a) || NotInt(a + 1) || NotInt(a + 2)) return errWrongType; QSize new_size(QtCollider::read<int>(a), QtCollider::read<int>(a + 1)); int resize_mode = QtCollider::read<int>(a + 2); Image* image = to_image(r); if (image->isPainting()) { qcErrorMsg("QImage: can not resize while being painted."); return errFailed; } image->resize(new_size, resize_mode); return errNone; } QC_LANG_PRIMITIVE(QImage_Write, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QString path = QC::get(a); QString format = QC::get(a + 1); if (NotInt(a + 2)) return errWrongType; int quality = QC::read<int>(a + 2); QImage& image = to_image(r)->image(); if (image.save(path, format.toUpper().toStdString().c_str(), quality)) return errNone; qcErrorMsg(QStringLiteral("QImage: Failed to write to file: ") + path); return errFailed; } QC_LANG_PRIMITIVE(QImage_SetPainter, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (QtCollider::paintingAnnounced()) { qcDebugMsg(1, "WARNING: Custom painting already in progress. Will not paint."); return errFailed; } Image* image = to_image(r); assert(!image->isPainting()); assert(imgPainter == 0); imgPainter = new QPainter(&image->image()); QtCollider::announcePainting(); QtCollider::beginPainting(imgPainter); image->setPainting(true); return errNone; } QC_LANG_PRIMITIVE(QImage_UnsetPainter, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); assert(image->isPainting()); image->setPainting(false); assert(imgPainter != 0); QtCollider::endPainting(); delete imgPainter; imgPainter = 0; return errNone; } QC_LANG_PRIMITIVE(QImage_GetPixel, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a) || NotInt(a + 1)) return errWrongType; int x = QC::read<int>(a); int y = QC::read<int>(a + 1); QImage& image = to_image(r)->image(); if (x >= image.width() || y >= image.height()) return errIndexOutOfRange; int* line = reinterpret_cast<int*>(image.scanLine(y)); SetInt(r, line[x]); return errNone; } QC_LANG_PRIMITIVE(QImage_GetColor, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a) || NotInt(a + 1)) return errWrongType; int x = QC::read<int>(a); int y = QC::read<int>(a + 1); QImage& image = to_image(r)->image(); if (x >= image.width() || y >= image.height()) return errIndexOutOfRange; QRgb* line = reinterpret_cast<QRgb*>(image.scanLine(y)); QC::set(r, pixel_to_color(line[x])); return errNone; } QC_LANG_PRIMITIVE(QImage_SetPixel, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a) || NotInt(a + 1) || NotInt(a + 2)) return errWrongType; int pixel = QC::read<int>(a); int x = QC::read<int>(a + 1); int y = QC::read<int>(a + 2); QImage& image = to_image(r)->image(); if (x >= image.width() || y >= image.height()) return errIndexOutOfRange; int* line = reinterpret_cast<int*>(image.scanLine(y)); line[x] = pixel; return errNone; } QC_LANG_PRIMITIVE(QImage_SetColor, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotObj(a) || slotRawObject(a)->classptr != SC_CLASS(Color) || NotInt(a + 1) || NotInt(a + 2)) return errWrongType; QColor color(QC::read<QColor>(a)); int x = QC::read<int>(a + 1); int y = QC::read<int>(a + 2); QImage& image = to_image(r)->image(); if (x >= image.width() || y >= image.height()) return errIndexOutOfRange; QRgb* line = reinterpret_cast<QRgb*>(image.scanLine(y)); line[x] = color_to_pixel(color); return errNone; } QC_LANG_PRIMITIVE(QImage_TransferPixels, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (!isKindOfSlot(a, class_int32array)) { qcErrorMsg("QImage: array argument is not a Int32Array"); return errWrongType; } if (NotInt(a + 2)) return errWrongType; int start = QC::read<int>(a + 2); if (!(IsTrue(a + 3) || IsFalse(a + 3))) return errWrongType; bool store = IsTrue(a + 3); // t/f g/s QImage& image = to_image(r)->image(); QRect rect; if (IsNil(a + 1)) { rect = image.rect(); } else { if (!isKindOfSlot(a + 1, SC_CLASS(Rect))) return errWrongType; rect = QC::read<QRect>(a + 1); if (rect.isEmpty()) return errNone; if (!image.rect().contains(rect)) { qcErrorMsg("QImage: source rectangle out of image bounds"); return errFailed; } } PyrInt32Array* array = reinterpret_cast<PyrInt32Array*>(slotRawObject(a)); QRgb* pixelData = reinterpret_cast<QRgb*>(array->i) + start; int width = rect.width(); int height = rect.height(); int size = width * height; int x = rect.x(); int y = rect.y(); int max_x = width + x; int max_y = height + y; if (array->size - start < size) return errIndexOutOfRange; if (store) { for (int iy = y; iy < max_y; ++iy) { QRgb* line = reinterpret_cast<QRgb*>(image.scanLine(iy)); for (int ix = x; ix < max_x; ++ix) { line[ix] = *pixelData; ++pixelData; } } } else { for (int iy = y; iy < max_y; ++iy) { QRgb* line = reinterpret_cast<QRgb*>(image.scanLine(iy)); for (int ix = x; ix < max_x; ++ix) { *pixelData = line[ix]; ++pixelData; } } } return errNone; } QC_LANG_PRIMITIVE(QImage_Fill, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotObj(a) || slotRawObject(a)->classptr != SC_CLASS(Color)) return errWrongType; QColor color = QC::read<QColor>(a); QImage& image = to_image(r)->image(); image.fill(color_to_pixel(color)); return errNone; } QC_LANG_PRIMITIVE(QImage_Formats, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); if (NotInt(a)) return errWrongType; int rw = QC::read<int>(a); QList<QByteArray> formats = rw ? QImageWriter::supportedImageFormats() : QImageReader::supportedImageFormats(); PyrObject* array = newPyrArray(g->gc, formats.size(), 0, true); SetObject(r, array); for (int i = 0; i < formats.size(); ++i) { PyrString* str = newPyrString(g->gc, formats[i].constData(), obj_immutable, false); SetObject(array->slots + i, str); ++array->size; g->gc->GCWriteNew(array, str); // we know str is white so we can use GCWriteNew } return errNone; } QC_LANG_PRIMITIVE(QImage_PixelToColor, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotInt(a)) return errWrongType; QRgb pixel = static_cast<QRgb>(QC::read<int>(a)); QC::set(r, pixel_to_color(pixel)); return errNone; } QC_LANG_PRIMITIVE(QImage_ColorToPixel, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotObj(a) || slotRawObject(a)->classptr != SC_CLASS(Color)) return errWrongType; QColor color = QC::read<QColor>(a); int pixel = static_cast<int>(color_to_pixel(color)); QC::set(r, pixel); return errNone; } QC_LANG_PRIMITIVE(QImage_GetDevicePixelRatio, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); Image* image = to_image(r); SetFloat(r, image->getDevicePixelRatio()); return errNone; } QC_LANG_PRIMITIVE(QImage_SetDevicePixelRatio, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); double ratio = 1; int err = slotDoubleVal(a, &ratio); if (err == errNone) { Image* image = to_image(r); image->setDevicePixelRatio(ratio); } return err; } void defineQImagePrimitives() { LangPrimitiveDefiner definer; definer.define<QImage_NewPath>(); definer.define<QImage_NewSVG>(); definer.define<QImage_NewURL>(); definer.define<QImage_NewEmpty>(); definer.define<QImage_NewFromWindow>(); definer.define<QImage_Free>(); definer.define<QImage_HasSmoothTransformation>(); definer.define<QImage_SetSmoothTransformation>(); definer.define<QImage_Width>(); definer.define<QImage_Height>(); definer.define<QImage_SetSize>(); definer.define<QImage_Write>(); definer.define<QImage_SetPainter>(); definer.define<QImage_UnsetPainter>(); definer.define<QImage_GetPixel>(); definer.define<QImage_GetColor>(); definer.define<QImage_SetPixel>(); definer.define<QImage_SetColor>(); definer.define<QImage_TransferPixels>(); definer.define<QImage_Fill>(); definer.define<QImage_Formats>(); definer.define<QImage_PixelToColor>(); definer.define<QImage_ColorToPixel>(); definer.define<QImage_GetDevicePixelRatio>(); definer.define<QImage_SetDevicePixelRatio>(); } } // namespace QtCollider
17,908
C++
.cpp
474
32.535865
115
0.65292
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,800
prim_QPalette.cpp
supercollider_supercollider/QtCollider/primitives/prim_QPalette.cpp
/************************************************************************ * * Copyright 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "prim_QPalette.hpp" #include "primitives.h" #include "../Common.h" #include "../type_codec.hpp" #include <PyrKernel.h> #include <QPalette> #include <cassert> namespace QtCollider { int QPalette_Finalize(struct VMGlobals* g, struct PyrObject* obj) { delete QPALETTE_FROM_OBJECT(obj); return errNone; } void QPalette_Init(struct VMGlobals* g, struct PyrObject* obj, const QPalette& palette) { assert(obj->classptr == SC_CLASS(QPalette)); assert(IsNil(obj->slots) && IsNil(obj->slots + 1)); QPalette* p = new QPalette(palette); SetPtr(obj->slots, p); InstallFinalizer(g, obj, 1, QPalette_Finalize); } QC_LANG_PRIMITIVE(QPalette_New, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPalette_Init(g, slotRawObject(r)); return errNone; } QC_LANG_PRIMITIVE(QPalette_Auto, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QColor button = QtCollider::get(a); QColor window = QtCollider::get(a + 1); QPalette_Init(g, slotRawObject(r), QPalette(button, window)); return errNone; } QC_LANG_PRIMITIVE(QPalette_System, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPalette_Init(g, slotRawObject(r), QtCollider::systemPalette()); return errNone; } QC_LANG_PRIMITIVE(QPalette_Color, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPalette* p = QPALETTE_FROM_OBJECT(slotRawObject(r)); if (NotInt(a)) return errWrongType; QPalette::ColorRole role = (QPalette::ColorRole)(slotRawInt(a)); if (IsInt(a + 1)) { QPalette::ColorGroup group = (QPalette::ColorGroup)(slotRawInt(a + 1)); QtCollider::set(r, p->color(group, role)); } else { QtCollider::set(r, p->color(role)); } return errNone; } QC_LANG_PRIMITIVE(QPalette_SetColor, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPalette* p = QPALETTE_FROM_OBJECT(slotRawObject(r)); QColor color = QtCollider::get(a); if (NotInt(a + 1)) return errWrongType; QPalette::ColorRole role = (QPalette::ColorRole)(slotRawInt(a + 1)); if (IsInt(a + 2)) { QPalette::ColorGroup group = (QPalette::ColorGroup)(slotRawInt(a + 2)); p->setColor(group, role, color); } else { p->setColor(role, color); } return errNone; } QC_LANG_PRIMITIVE(QPalette_HasColor, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPalette* p = QPALETTE_FROM_OBJECT(slotRawObject(r)); if (NotInt(a)) return errWrongType; QPalette::ColorRole role = (QPalette::ColorRole)(slotRawInt(a)); QPalette::ColorGroup group; group = IsInt(a + 1) ? (QPalette::ColorGroup)(slotRawInt(a + 1)) : QPalette::Normal; SetBool(r, p->isBrushSet(group, role)); return errNone; } void defineQPalettePrimitives() { LangPrimitiveDefiner definer; definer.define<QPalette_New>(); definer.define<QPalette_Auto>(); definer.define<QPalette_System>(); definer.define<QPalette_Color>(); definer.define<QPalette_SetColor>(); definer.define<QPalette_HasColor>(); } } // namespace QtCollider
3,907
C++
.cpp
100
35.13
89
0.671958
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,801
prim_QObject.cpp
supercollider_supercollider/QtCollider/primitives/prim_QObject.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "../QObjectProxy.h" #include "../QcObjectFactory.h" #include "../QcApplication.h" #include "../Common.h" #include "../type_codec.hpp" #include "../metatype.hpp" #include "../painting.h" #include <PyrObject.h> #include <PyrKernel.h> #include <GC.h> #include <SCBase.h> #include <QMetaObject> #include <QMetaProperty> #include <QMetaMethod> #if defined _WIN32 # include "SC_Win32Utils.h" #elif defined __FreeBSD__ || defined __OpenBSD__ # include <stdlib.h> #else # include <alloca.h> #endif #define IS_OBJECT_NIL(a) IsNil(slotRawObject(a)->slots) #define QOBJECT_FROM_SLOT(s) ((QObjectProxy*)slotRawPtr(slotRawObject(s)->slots)) #define CLASS_NAME(slot) slotRawSymbol(&slotRawObject(slot)->classptr->name)->name namespace QtCollider { int QObject_Finalize(struct VMGlobals*, struct PyrObject*); QC_LANG_PRIMITIVE(QObject_New, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0)) return errWrongType; PyrObject* scObject = slotRawObject(r); QString qtClassName = QString(slotRawSymbol(a + 0)->name); qcSCObjectDebugMsg(1, scObject, QStringLiteral("CREATE: %2").arg(qtClassName)); if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); QcAbstractFactory* f = QtCollider::factories().value(qtClassName); if (!f) { qcErrorMsg(QStringLiteral("Factory for class '%1' not found!").arg(qtClassName)); return errFailed; } QObjectProxy* proxy = 0; MetaValue args[10]; PyrSlot* argSlot = a + 1; int argc; if (isKindOfSlot(argSlot, class_array)) { PyrObject* array = slotRawObject(argSlot); argSlot = array->slots; argc = array->size; } else { argc = 1; } for (int i = 0; i < argc && i < 10; ++i) { PyrSlot* slot = argSlot + i; MetaType* type = MetaType::find(slot); if (type) { void* mem = alloca(type->size()); Q_ASSERT(mem); args[i].read(mem, type, slot); } } proxy = f->newInstance(scObject, args); if (!proxy) return errFailed; SetPtr(scObject->slots, proxy); InstallFinalizer(g, scObject, 1, QObject_Finalize); return errNone; } QC_LANG_PRIMITIVE(QObject_Destroy, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { qcSCObjectDebugMsg(1, slotRawObject(r), "DESTROY"); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); // Post the destruction event asynchronously; DestroyEvent* e = new DestroyEvent(QObjectProxy::DestroyObject); QApplication::postEvent(proxy, e); return errNone; } int QObject_Finalize(struct VMGlobals*, struct PyrObject* obj) { qcSCObjectDebugMsg(1, obj, "FINALIZE"); QObjectProxy* proxy = (QObjectProxy*)slotRawPtr(obj->slots); // Invalidate proxy's SC object pointer directly. // Note that it is protected by language mutex; proxy->finalize(); // Post the destruction event asynchronously; DestroyEvent* e = new DestroyEvent(QObjectProxy::DestroyProxyAndObject); QApplication::postEvent(proxy, e); return errNone; } QC_LANG_PRIMITIVE(QObject_SetParent, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); QObjectProxy* parent = QtCollider::get(a); if (!parent) return errWrongType; qcSCObjectDebugMsg(1, slotRawObject(r), "SET PARENT"); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->setParent(parent); return ok ? errNone : errFailed; } static void qcGetProperties(const QMetaObject* mo, PyrSlot* r, VMGlobals* g) { int count = mo->propertyCount(); PyrObject* array = newPyrArray(g->gc, count, 0, true); SetObject(r, array); PyrSlot* s = array->slots; for (int i = 0; i < count; ++i, ++s) { SetSymbol(s, getsym(mo->property(i).name())); array->size++; } } static void qcGetMethods(const QMetaObject* mo, bool getPlain, bool getSignals, bool getSlots, PyrSlot* r, VMGlobals* g) { int count = mo->methodCount(); PyrObject* array = newPyrArray(g->gc, count, 0, true); SetObject(r, array); PyrSlot* s = array->slots; for (int i = 0; i < count; ++i) { QMetaMethod method = mo->method(i); switch (method.methodType()) { case QMetaMethod::Method: if (!getPlain || (method.access() != QMetaMethod::Public)) continue; break; case QMetaMethod::Signal: if (!getSignals) continue; break; case QMetaMethod::Slot: if (!getSlots || (method.access() != QMetaMethod::Public)) continue; break; default: continue; } QtCollider::set(s, QString::fromLatin1(method.methodSignature())); array->size++; g->gc->GCWrite(array, s); ++s; } } QC_LANG_PRIMITIVE(QMetaObject_Properties, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); PyrSlot* sClassName = slotRawObject(r)->slots + 0; if (NotSym(sClassName)) return errWrongType; QString className(slotRawSymbol(sClassName)->name); QcAbstractFactory* f = QtCollider::factories().value(className); if (!f) { qcErrorMsg(QStringLiteral("Factory for class '%1' not found!").arg(className)); return errFailed; } const QMetaObject* mo = f->metaObject(); qcGetProperties(mo, r, g); return errNone; } QC_LANG_PRIMITIVE(QMetaObject_Methods, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!QcApplication::compareThread()) return QtCollider::wrongThreadError(); PyrSlot* sClassName = slotRawObject(r)->slots + 0; if (NotSym(sClassName)) return errWrongType; QString className(slotRawSymbol(sClassName)->name); QcAbstractFactory* f = QtCollider::factories().value(className); if (!f) { qcErrorMsg(QStringLiteral("Factory for class '%1' not found!").arg(className)); return errFailed; } bool getPlain = IsTrue(a + 0); bool getSignals = IsTrue(a + 1); bool getSlots = IsTrue(a + 2); const QMetaObject* mo = f->metaObject(); qcGetMethods(mo, getPlain, getSignals, getSlots, r, g); return errNone; } QC_LANG_PRIMITIVE(QObject_GetProperties, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QObject* obj = proxy->object(); if (!obj) { SetNil(r); return errNone; } const QMetaObject* mo = obj->metaObject(); qcGetProperties(mo, r, g); return errNone; } QC_LANG_PRIMITIVE(QObject_GetMethods, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QObject* obj = proxy->object(); if (!obj) { SetNil(r); return errNone; } bool getPlain = IsTrue(a + 0); bool getSignals = IsTrue(a + 1); bool getSlots = IsTrue(a + 2); const QMetaObject* mo = obj->metaObject(); qcGetMethods(mo, getPlain, getSignals, getSlots, r, g); return errNone; } QC_LANG_PRIMITIVE(QObject_SetProperty, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (NotSym(a)) return errWrongType; PyrSymbol* property = slotRawSymbol(a); bool sync = IsTrue(a + 2); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("SET: %1").arg(property->name)); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QVariant val = QtCollider::get(a + 1); if (sync && !QtCollider::isPaintingObject(proxy)) { proxy->setProperty(property->name, val); } else { SetPropertyEvent* e = new SetPropertyEvent(); e->property = property; e->value = val; QApplication::postEvent(proxy, e); } return errNone; } QC_LANG_PRIMITIVE(QObject_GetProperty, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (NotSym(a)) return errWrongType; PyrSymbol* symProp = slotRawSymbol(a); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("GET: %1").arg(symProp->name)); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QVariant val = proxy->property(symProp->name); if (!val.isValid()) { qcDebugMsg(1, QStringLiteral("WARNING: Invalid property '%1'").arg(symProp->name)); SetNil(r); return errNone; } if (QtCollider::set(r, val)) return errNone; else return errFailed; } QC_LANG_PRIMITIVE(QObject_SetEventHandler, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (NotInt(a + 0) || NotSym(a + 1)) return errWrongType; int eventType = QtCollider::get(a + 0); PyrSymbol* method = 0; slotSymbolVal(a + 1, &method); Synchronicity sync = IsTrue(a + 2) ? Synchronous : Asynchronous; bool enabled = IsTrue(a + 3); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("SET EVENT HANDLER: type %1 -> %2 [%3, %4]") .arg(eventType) .arg(method->name) .arg(sync == Synchronous ? "SYNC" : "ASYNC") .arg(enabled ? "on" : "off")); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->setEventHandler(eventType, method, sync, enabled); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_SetEventHandlerEnabled, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotInt(a + 0)) return errWrongType; bool enabled = IsTrue(a + 1); if (!enabled && !IsFalse(a + 1)) return errWrongType; int type = QtCollider::get(a + 0); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("SET EVENT HANDLER STATE: type %1 = %2").arg(type).arg(enabled ? "on" : "off")); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->setEventHandlerEnabled(type, enabled); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_ConnectMethod, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0) || NotSym(a + 1)) return errWrongType; PyrSymbol* signal = slotRawSymbol(a + 0); PyrSymbol* handler = slotRawSymbol(a + 1); Qt::ConnectionType ctype = IsTrue(a + 2) ? Qt::DirectConnection : Qt::QueuedConnection; qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("CONNECT METHOD: %1 -> %2 [%3]") .arg(signal->name) .arg(handler->name) .arg(IsTrue(a + 2) ? "SYNC" : "ASYNC")); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->connectMethod(signal->name, handler, ctype); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_DisconnectMethod, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0) || NotSym(a + 1)) return errWrongType; PyrSymbol* signal = slotRawSymbol(a + 0); PyrSymbol* handler = slotRawSymbol(a + 1); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("DISCONNECT METHOD: %1 -> %2").arg(signal->name).arg(handler->name)); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->disconnectMethod(signal->name, handler); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_ConnectObject, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0) || NotObj(a + 1)) return errWrongType; PyrSymbol* signal = slotRawSymbol(a + 0); PyrObject* handlerObj = slotRawObject(a + 1); Qt::ConnectionType ctype = IsTrue(a + 2) ? Qt::DirectConnection : Qt::QueuedConnection; qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("CONNECT OBJECT: %1 -> %2 [%3]") .arg(signal->name) .arg(slotRawSymbol(&handlerObj->classptr->name)->name) .arg(IsTrue(a + 2) ? "SYNC" : "ASYNC")); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->connectObject(signal->name, handlerObj, ctype); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_DisconnectObject, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0) || NotObj(a + 1)) return errWrongType; PyrSymbol* signal = slotRawSymbol(a + 0); PyrObject* handlerObj = slotRawObject(a + 1); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("DISCONNECT OBJECT: %1").arg(signal->name)); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); bool ok = proxy->disconnectObject(signal->name, handlerObj); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_ConnectSlot, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { // Args: signal, receiver, slot if (!isKindOfSlot(a + 1, SC_CLASS(QObject)) || NotSym(a + 0) || NotSym(a + 2)) return errWrongType; PyrSymbol* symSig = slotRawSymbol(a + 0); PyrSymbol* symSlot = slotRawSymbol(a + 2); QObjectProxy* sndProxy = QOBJECT_FROM_SLOT(r); QObjectProxy* rcvProxy = QOBJECT_FROM_SLOT(a + 1); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("CONNECT TO SLOT: %1 -> %2").arg(symSig->name).arg(symSlot->name)); QString strSig = QStringLiteral("2") + symSig->name; QString strSlot = QStringLiteral("1") + symSlot->name; sndProxy->lock(); rcvProxy->lock(); bool ok; if (!sndProxy->object() || !rcvProxy->object()) { ok = true; } else { ok = QObject::connect(sndProxy->object(), strSig.toStdString().c_str(), rcvProxy->object(), strSlot.toStdString().c_str()); } sndProxy->unlock(); rcvProxy->unlock(); if (!ok) { qcErrorMsg(QStringLiteral("Failed to connect %1::%2 to %3::%4!\n") .arg(sndProxy->scClassName()) .arg(symSig->name) .arg(rcvProxy->scClassName()) .arg(symSlot->name)); return errFailed; } return errNone; } QC_LANG_PRIMITIVE(QObject_InvokeMethod, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a + 0)) return errWrongType; PyrSymbol* method = slotRawSymbol(a + 0); PyrSlot* methodArgs = a + 1; bool sync = !IsFalse(a + 2); qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("INVOKE: '%1' [%2]").arg(method->name).arg(sync ? "SYNC" : "ASYNC")); QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); PyrSlot* retSlot; Qt::ConnectionType cType; if (sync) { if (!proxy->compareThread()) return QtCollider::wrongThreadError(); retSlot = r; cType = Qt::DirectConnection; } else { retSlot = 0; cType = Qt::QueuedConnection; } bool ok = proxy->invokeMethod(method->name, retSlot, methodArgs, cType); return ok ? errNone : errFailed; } QC_LANG_PRIMITIVE(QObject_IsValid, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); bool needLock = !proxy->compareThread(); if (needLock) proxy->lock(); bool hasObject = proxy->object() != 0; if (needLock) proxy->unlock(); SetBool(r, hasObject); return errNone; } QC_LANG_PRIMITIVE(QObject_GetChildren, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a) && NotNil(a)) return errWrongType; QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); PyrSymbol* className = IsSym(a) ? slotRawSymbol(a) : 0; qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("GET CHILDREN: of class '%1'").arg(className ? className->name : "QObject")); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); QList<PyrObject*> children = proxy->children(className); int count = children.count(); PyrObject* array = newPyrArray(g->gc, count, 0, true); SetObject(r, array); PyrSlot* s = array->slots; Q_FOREACH (PyrObject* obj, children) { SetObject(s, obj); ++array->size; g->gc->GCWrite(array, s); ++s; } return errNone; } QC_LANG_PRIMITIVE(QObject_GetParent, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (NotSym(a) && NotNil(a)) return errWrongType; QObjectProxy* proxy = QOBJECT_FROM_SLOT(r); PyrSymbol* className = IsSym(a) ? slotRawSymbol(a) : 0; qcSCObjectDebugMsg(1, slotRawObject(r), QStringLiteral("GET PARENT")); if (!proxy->compareThread()) return QtCollider::wrongThreadError(); PyrObject* parent = proxy->parent(className); if (parent) SetObject(r, parent); else SetNil(r); return errNone; } void defineQObjectPrimitives() { LangPrimitiveDefiner definer; definer.define<QObject_New>(); definer.define<QObject_Destroy>(); definer.define<QObject_SetParent>(); definer.define<QMetaObject_Properties>(); definer.define<QMetaObject_Methods>(); definer.define<QObject_GetProperties>(); definer.define<QObject_GetMethods>(); definer.define<QObject_SetProperty>(); definer.define<QObject_GetProperty>(); definer.define<QObject_SetEventHandler>(); definer.define<QObject_SetEventHandlerEnabled>(); definer.define<QObject_ConnectMethod>(); definer.define<QObject_DisconnectMethod>(); definer.define<QObject_ConnectObject>(); definer.define<QObject_DisconnectObject>(); definer.define<QObject_ConnectSlot>(); definer.define<QObject_InvokeMethod>(); definer.define<QObject_IsValid>(); definer.define<QObject_GetChildren>(); definer.define<QObject_GetParent>(); } } // namespace QtCollider
19,457
C++
.cpp
484
33.555785
118
0.639239
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,802
primitives.cpp
supercollider_supercollider/QtCollider/primitives/primitives.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "../Common.h" #include "QtCollider.h" #include <SCBase.h> namespace QtCollider { #define QC_DO_SYMBOL(SYM) PyrSymbol* sym_##SYM QC_DO_SYMBOLS #undef QC_DO_SYMBOL void defineQObjectPrimitives(); void defineQPenPrimitives(); void defineMiscPrimitives(); void defineQWidgetPrimitives(); void defineQPalettePrimitives(); void defineQImagePrimitives(); #if defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) void defineQcQuartzComposerPrimitives(); #endif void initPrimitives() { QtCollider::init(); qcDebugMsg(1, "initializing QtGUI primitives"); defineQObjectPrimitives(); defineQWidgetPrimitives(); defineQPenPrimitives(); defineMiscPrimitives(); defineQPalettePrimitives(); defineQImagePrimitives(); #if defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) defineQcQuartzComposerPrimitives(); #endif #define QC_DO_SYMBOL(SYM) sym_##SYM = getsym(#SYM); QC_DO_SYMBOLS #undef QC_DO_SYMBOL } } // namespace QtCollider
1,932
C++
.cpp
54
33.462963
74
0.698285
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,803
prim_QPen.cpp
supercollider_supercollider/QtCollider/primitives/prim_QPen.cpp
/************************************************************************ * * Copyright 2010-2013 Jakob Leben (jakob.leben@gmail.com) * Copyright 2010 Ivan Leben (ivan.leben@gmail.com) (QPen_ArcTo) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "primitives.h" #include "../painting.h" #include "../image.h" #include "../type_codec.hpp" #include "PyrKernel.h" #include <QPainter> #include <QPainterPath> #include <QVector2D> #include <QVector3D> #include <cmath> static bool announced = false; static QObject* paintingObject = NULL; static QPainter* painter = 0; static QPainterPath path; namespace QtCollider { void announcePainting() { announced = true; } bool paintingAnnounced() { return announced; } bool isPaintingObject(QObject* obj) { return obj == paintingObject; } bool beginPainting(QPainter* p, QObject* obj) { if (painter) { qcErrorMsg(QStringLiteral("Painting already in progress!")); return false; } painter = p; paintingObject = obj; painter->setRenderHint(QPainter::Antialiasing, true); QColor black(0, 0, 0); QPen pen(black); pen.setCapStyle(Qt::FlatCap); painter->setPen(pen); painter->setBrush(black); path = QPainterPath(); return true; } void endPainting() { painter = 0; announced = false; paintingObject = NULL; } QPainter* globalPainter() { return painter; } } typedef QVector2D vec2; typedef QVector3D vec3; static const double PI = 3.14159265358979323846264338327950288419717; inline static qreal globalAngle(const vec2& v) { // assuming v is normalized qreal cosa = v.x(); qreal sina = -v.y(); return sina >= 0.0 ? acosf(cosa) : 2.0 * PI - acosf(cosa); } inline static qreal vectorAngle(const vec2& v1, const vec2& v2) { // assuming v1,v2 are normalized return acosf(vec2::dotProduct(v1, v2)); } inline static qreal signedAngle(const vec2& v1, const vec2& v2) { // assuming v1,v2 are normalized qreal a = vectorAngle(v1, v2); vec3 c = vec3::crossProduct(vec3(v1), vec3(v2)); return c.z() > 0.0 ? a : -a; } inline static qreal radToDeg(qreal rad) { return rad * 180.0 / PI; } inline static bool isPenValid() { if (!painter) { qcErrorMsg(QStringLiteral("Usage of QPen is not allowed at this point!")); return false; } return true; } #define QC_QPEN_PRIMITIVE(NAME, ARGC, RECEIVER, ARGS, GLOBAL) \ struct NAME {}; \ template <> struct LangPrimitive<NAME> { \ static int implementation(RECEIVER, ARGS, GLOBAL); \ static int mediate(VMGlobals* g, int i) { \ if (!isPenValid()) \ return errFailed; \ PyrSlot* stack = g->sp - i + 1; \ return implementation(stack, i > 1 ? stack + 1 : 0, g); \ } \ static void define(int base, int index) { definePrimitive(base, index, "_" #NAME, &mediate, ARGC + 1, 0); } \ }; \ int LangPrimitive<NAME>::implementation(RECEIVER, ARGS, GLOBAL) namespace QtCollider { QC_QPEN_PRIMITIVE(QPen_Save, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { painter->save(); return errNone; } QC_QPEN_PRIMITIVE(QPen_Restore, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { painter->restore(); return errNone; } QC_QPEN_PRIMITIVE(QPen_Clear, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { path = QPainterPath(); return errNone; } QC_QPEN_PRIMITIVE(QPen_FillColor, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QColor color = QtCollider::get(a); painter->setBrush(color); return errNone; } QC_QPEN_PRIMITIVE(QPen_StrokeColor, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QColor color = QtCollider::get(a); QPen pen = painter->pen(); pen.setColor(color); painter->setPen(pen); return errNone; } QC_QPEN_PRIMITIVE(QPen_Width, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float width; if (slotFloatVal(a, &width)) return errWrongType; QPen pen = painter->pen(); pen.setWidthF(width); painter->setPen(pen); return errNone; } QC_QPEN_PRIMITIVE(QPen_SetJoinStyle, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { int style = QtCollider::get(a); QPen pen = painter->pen(); switch (style) { case 0: pen.setJoinStyle(Qt::MiterJoin); break; case 1: pen.setJoinStyle(Qt::RoundJoin); break; case 2: pen.setJoinStyle(Qt::BevelJoin); break; default: return errFailed; } painter->setPen(pen); return errNone; } QC_QPEN_PRIMITIVE(QPen_SetCapStyle, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { int style = QtCollider::get(a); QPen pen = painter->pen(); switch (style) { case 0: pen.setCapStyle(Qt::FlatCap); break; case 1: pen.setCapStyle(Qt::RoundCap); break; case 2: pen.setCapStyle(Qt::SquareCap); break; default: return errFailed; } painter->setPen(pen); return errNone; } QC_QPEN_PRIMITIVE(QPen_SetDashPattern, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (!IsObj(a)) return errWrongType; PyrObject* obj = slotRawObject(a); if (obj->classptr != class_floatarray) return errWrongType; PyrFloatArray* farray = reinterpret_cast<PyrFloatArray*>(obj); int s = farray->size; float* f = farray->f; QVector<qreal> pattern; int i = 1; while (i < s) { pattern << *f << *(f + 1); f += 2; i += 2; } if (pattern.size()) { QPen pen = painter->pen(); pen.setDashPattern(pattern); painter->setPen(pen); } return errNone; } QC_QPEN_PRIMITIVE(QPen_SetOpacity, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float opacity = QtCollider::get(a); painter->setOpacity(opacity); return errNone; } QC_QPEN_PRIMITIVE(QPen_Clip, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { painter->setClipPath(path); path = QPainterPath(); return errNone; } QC_QPEN_PRIMITIVE(QPen_AntiAliasing, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { bool b = IsTrue(a); if (!b && !IsFalse(a)) return errWrongType; painter->setRenderHint(QPainter::Antialiasing, b); return errNone; } QC_QPEN_PRIMITIVE(QPen_SetFont, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { painter->setFont(QtCollider::get(a)); return errNone; } QC_QPEN_PRIMITIVE(QPen_Translate, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float x, y; if (slotFloatVal(a, &x)) return errWrongType; if (slotFloatVal(a + 1, &y)) return errWrongType; painter->translate(x, y); return errNone; } QC_QPEN_PRIMITIVE(QPen_Scale, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float x, y; if (slotFloatVal(a, &x)) return errWrongType; if (slotFloatVal(a + 1, &y)) return errWrongType; painter->scale(x, y); return errNone; } QC_QPEN_PRIMITIVE(QPen_Shear, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float x, y; if (slotFloatVal(a, &x)) return errWrongType; if (slotFloatVal(a + 1, &y)) return errWrongType; painter->shear(x, y); return errNone; } QC_QPEN_PRIMITIVE(QPen_Rotate, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float angle, x, y; if (slotFloatVal(a, &angle)) return errWrongType; if (slotFloatVal(a + 1, &x)) return errWrongType; if (slotFloatVal(a + 2, &y)) return errWrongType; painter->translate(x, y); painter->rotate(angle); painter->translate(-x, -y); return errNone; } QC_QPEN_PRIMITIVE(QPen_SetTransform, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QVariantList list = QtCollider::get(a); if (list.count() < 6) return errWrongType; float f[6]; int i = 6; while (i) { --i; const QVariant& var = list[i]; if (!var.canConvert(QVariant::Double)) return errWrongType; f[i] = var.value<float>(); } QTransform transform(f[0], f[1], f[2], f[3], f[4], f[5]); painter->setWorldTransform(transform, true); return errNone; } QC_QPEN_PRIMITIVE(QPen_Transform, 0, PyrSlot* r, PyrSlot* a, VMGlobals* g) { const QTransform& transform = painter->worldTransform(); PyrDoubleArray* doubleArray = newPyrDoubleArray(g->gc, 6, 0, true); SetObject(r, doubleArray); double* val = doubleArray->d; val[0] = transform.m11(); val[1] = transform.m12(); val[2] = transform.m21(); val[3] = transform.m22(); val[4] = transform.dx(); val[5] = transform.dy(); doubleArray->size = 6; return errNone; } QC_QPEN_PRIMITIVE(QPen_MoveTo, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF point = QtCollider::get(a); path.moveTo(point); return errNone; } QC_QPEN_PRIMITIVE(QPen_LineTo, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF point = QtCollider::get(a); path.lineTo(point); return errNone; } QC_QPEN_PRIMITIVE(QPen_CubicTo, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF endPoint = QtCollider::get(a); QPointF cPoint1 = QtCollider::get(a + 1); QPointF cPoint2 = QtCollider::get(a + 2); path.cubicTo(cPoint1, cPoint2, endPoint); return errNone; } QC_QPEN_PRIMITIVE(QPen_QuadTo, 2, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF endPoint = QtCollider::get(a); QPointF cPoint = QtCollider::get(a + 1); path.quadTo(cPoint, endPoint); return errNone; } QC_QPEN_PRIMITIVE(QPen_ArcTo, 3, PyrSlot* r, PyrSlot* arg, VMGlobals* g) { QPointF pt1 = QtCollider::get(arg); QPointF pt2 = QtCollider::get(arg + 1); float radius; if (slotFloatVal(arg + 2, &radius)) return errWrongType; radius = qMax(0.f, radius); vec2 a(path.currentPosition()); vec2 b(pt1); vec2 c(pt2); vec2 va = (a - b).normalized(); vec2 vc = (c - b).normalized(); vec2 m = (va + vc).normalized(); qreal lineAngle = vectorAngle(va, vc); qreal dm = radius / sinf(lineAngle * 0.5f); qreal dv = radius / tanf(lineAngle * 0.5f); vec2 center = b + dm * m; vec2 start = b + dv * va; vec2 end = b + dv * vc; vec2 vs = (start - center).normalized(); vec2 ve = (end - center).normalized(); qreal arcAngle = signedAngle(ve, vs); qreal arcStart = globalAngle(vs); path.lineTo(start.x(), start.y()); path.arcTo(center.x() - radius, center.y() - radius, 2 * radius, 2 * radius, radToDeg(arcStart), radToDeg(arcAngle)); // The current SC API does not want to pull the line to the last point. // Personally, I think it would be better: // path.lineTo( pt2 ); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddRect, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QRectF rect = QtCollider::get(a); path.addRect(rect); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddRoundedRect, 3, PyrSlot* r, PyrSlot* a, VMGlobals* g) { float radiusX, radiusY; QRectF rect; rect = QtCollider::get(a); if (slotFloatVal(a + 1, &radiusX)) return errWrongType; if (slotFloatVal(a + 2, &radiusY)) return errWrongType; path.addRoundedRect(rect, radiusX, radiusY); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddEllipse, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QRectF rect = QtCollider::get(a); path.addEllipse(rect); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddArc, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF center = QtCollider::get(a); float radius, startAngle, arcAngle; if (slotFloatVal(a + 1, &radius)) return errWrongType; if (slotFloatVal(a + 2, &startAngle)) return errWrongType; if (slotFloatVal(a + 3, &arcAngle)) return errWrongType; // have to swap angle direction for sinf() QPointF start(radius * cosf(startAngle), -radius * sinf(startAngle)); start += center; QRectF rect; rect.setSize(QSizeF(2 * radius, 2 * radius)); rect.moveCenter(center); path.moveTo(start); path.arcTo(rect, radToDeg(startAngle), radToDeg(arcAngle)); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddWedge, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF center = QtCollider::get(a); float radius, startAngle, sweepLength; if (slotFloatVal(a + 1, &radius)) return errWrongType; if (slotFloatVal(a + 2, &startAngle)) return errWrongType; if (slotFloatVal(a + 3, &sweepLength)) return errWrongType; path.moveTo(center); QRectF rect; rect.setSize(QSizeF(2 * radius, 2 * radius)); rect.moveCenter(center); path.arcTo(rect, startAngle, sweepLength); path.closeSubpath(); return errNone; } QC_QPEN_PRIMITIVE(QPen_AddAnnularWedge, 5, PyrSlot*, PyrSlot* a, VMGlobals* g) { QPointF c = QtCollider::get(a); float innerRadius, outerRadius, startAngle, arcAngle; if (slotFloatVal(a + 1, &innerRadius)) return errWrongType; if (slotFloatVal(a + 2, &outerRadius)) return errWrongType; if (slotFloatVal(a + 3, &startAngle)) return errWrongType; if (slotFloatVal(a + 4, &arcAngle)) return errWrongType; float saDeg = radToDeg(startAngle); float aaDeg = radToDeg(arcAngle); QPointF start(outerRadius * cosf(startAngle), -outerRadius * sinf(startAngle)); start += c; path.moveTo(start); QPointF pt(innerRadius, innerRadius); path.arcTo(QRectF(c - pt, c + pt), saDeg, aaDeg); pt = QPointF(outerRadius, outerRadius); path.arcTo(QRectF(c - pt, c + pt), saDeg + aaDeg, -aaDeg); return errNone; } QC_QPEN_PRIMITIVE(QPen_Draw, 1, PyrSlot* r, PyrSlot* a, VMGlobals* g) { if (path.isEmpty()) return errNone; int style = QtCollider::get(a); QPen pen = painter->pen(); QBrush brush = painter->brush(); switch (style) { case 0: case 1: painter->setPen(Qt::NoPen); break; case 2: painter->setBrush(Qt::NoBrush); break; case 3: case 4: default:; } if (style == 1 || style == 4) { path.setFillRule(Qt::OddEvenFill); } else { path.setFillRule(Qt::WindingFill); } painter->drawPath(path); path = QPainterPath(); painter->setPen(pen); painter->setBrush(brush); return errNone; } QC_QPEN_PRIMITIVE(QPen_FillAxialGradient, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF pt1 = QtCollider::get(a + 0); QPointF pt2 = QtCollider::get(a + 1); QColor c1 = QtCollider::get(a + 2); QColor c2 = QtCollider::get(a + 3); QLinearGradient grad(pt1, pt2); grad.setColorAt(0, c1); grad.setColorAt(1, c2); QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); painter->setBrush(grad); painter->drawPath(path); painter->setPen(pen); painter->setBrush(brush); path = QPainterPath(); return errNone; } QC_QPEN_PRIMITIVE(QPen_FillRadialGradient, 6, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QPointF pt1 = QtCollider::get(a + 0); QPointF pt2 = QtCollider::get(a + 1); float r1 = QtCollider::get(a + 2); float r2 = QtCollider::get(a + 3); QColor c1 = QtCollider::get(a + 4); QColor c2 = QtCollider::get(a + 5); QRadialGradient grad(pt2, r2, pt1); grad.setColorAt((r2 > 0 ? r1 / r2 : 0), c1); grad.setColorAt(1, c2); QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); painter->setBrush(grad); painter->drawPath(path); painter->setPen(pen); painter->setBrush(brush); path = QPainterPath(); return errNone; } QC_QPEN_PRIMITIVE(QPen_StringAtPoint, 4, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QString str = QtCollider::get(a); if (str.isEmpty()) return errNone; QPointF pt = QtCollider::get(a + 1); painter->save(); if (NotNil(a + 2)) painter->setFont(QtCollider::get(a + 2)); QPen pen(painter->pen()); pen.setColor(NotNil(a + 3) ? QtCollider::get(a + 3) : painter->brush().color()); painter->setPen(pen); QFont f(painter->font()); QFontMetrics fm(f); QRect rect = fm.boundingRect(str); painter->drawText(pt - rect.topLeft(), str); painter->restore(); return errNone; } QC_QPEN_PRIMITIVE(QPen_StringInRect, 5, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QString str = QtCollider::get(a); if (str.isEmpty()) return errNone; QRectF rect = QtCollider::get(a + 1); painter->save(); if (NotNil(a + 2)) painter->setFont(QtCollider::get(a + 2)); QPen pen(painter->pen()); pen.setColor(NotNil(a + 3) ? QtCollider::get(a + 3) : painter->brush().color()); painter->setPen(pen); Qt::Alignment align; if (NotNil(a + 4)) align = static_cast<Qt::Alignment>(QtCollider::get<int>(a + 4)); else align = Qt::AlignTop | Qt::AlignLeft; painter->drawText(rect, align, str); painter->restore(); return errNone; } QC_QPEN_PRIMITIVE(QPen_DrawImage, 5, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QtCollider::SharedImage image = QtCollider::get(a + 1); if (!image) return errWrongType; if (image->isPainting()) { qcErrorMsg("QImage: can not draw while being painted."); return errFailed; } QPixmap& pixmap = image->pixmap(); QRectF source; if (IsNil(a + 2)) source = QRectF(pixmap.rect()); else if (isKindOfSlot(a + 2, SC_CLASS(Rect))) source = QtCollider::read<QRectF>(a + 2); else return errWrongType; int composition = QtCollider::get(a + 3); float opacity = QtCollider::get(a + 4); painter->save(); painter->setCompositionMode((QPainter::CompositionMode)composition); painter->setRenderHint(QPainter::SmoothPixmapTransform, image->transformationMode == Qt::SmoothTransformation); painter->setOpacity(opacity); int result = errNone; if (isKindOfSlot(a + 0, SC_CLASS(Point))) { QPointF point = QtCollider::read<QPointF>(a + 0); painter->drawPixmap(point, pixmap, source); } else if (isKindOfSlot(a + 0, SC_CLASS(Rect))) { QRectF target = QtCollider::read<QRectF>(a + 0); painter->drawPixmap(target, pixmap, source); } else { result = errWrongType; } painter->restore(); return result; } QC_QPEN_PRIMITIVE(QPen_TileImage, 5, PyrSlot* r, PyrSlot* a, VMGlobals* g) { QtCollider::SharedImage image = QtCollider::get(a + 1); if (!image) return errWrongType; if (image->isPainting()) { qcErrorMsg("QImage: can not draw while being painted."); return errFailed; } QPixmap& pixmap = image->pixmap(); QRectF source; if (IsNil(a + 2)) source = QRectF(pixmap.rect()); else if (isKindOfSlot(a + 2, SC_CLASS(Rect))) source = QtCollider::read<QRectF>(a + 2); else return errWrongType; QRectF target; if (isKindOfSlot(a + 0, SC_CLASS(Rect))) target = QtCollider::read<QRectF>(a + 0); else return errWrongType; if (target.isEmpty() || source.isEmpty()) return errNone; int composition = QtCollider::get(a + 3); float opacity = QtCollider::get(a + 4); painter->save(); painter->setCompositionMode((QPainter::CompositionMode)composition); painter->setRenderHint(QPainter::SmoothPixmapTransform, image->transformationMode == Qt::SmoothTransformation); painter->setOpacity(opacity); painter->setClipRect(target); QRectF area = source; area.moveTo(target.topLeft()); float max_x = target.right(); float max_y = target.bottom(); int iter_x, iter_y; for (iter_y = 0;; ++iter_y) { area.moveTop(iter_y * source.height() + target.top()); if (area.top() > max_y) break; for (iter_x = 0;; ++iter_x) { area.moveLeft(iter_x * source.width() + target.left()); if (area.left() > max_x) break; painter->drawPixmap(area, pixmap, source); } } painter->restore(); return errNone; } void defineQPenPrimitives() { LangPrimitiveDefiner definer; definer.define<QPen_Save>(); definer.define<QPen_Restore>(); definer.define<QPen_Clear>(); definer.define<QPen_FillColor>(); definer.define<QPen_StrokeColor>(); definer.define<QPen_Width>(); definer.define<QPen_SetJoinStyle>(); definer.define<QPen_SetCapStyle>(); definer.define<QPen_SetDashPattern>(); definer.define<QPen_SetOpacity>(); definer.define<QPen_Clip>(); definer.define<QPen_AntiAliasing>(); definer.define<QPen_SetFont>(); definer.define<QPen_Translate>(); definer.define<QPen_Scale>(); definer.define<QPen_Shear>(); definer.define<QPen_Rotate>(); definer.define<QPen_Transform>(); definer.define<QPen_SetTransform>(); definer.define<QPen_MoveTo>(); definer.define<QPen_LineTo>(); definer.define<QPen_CubicTo>(); definer.define<QPen_QuadTo>(); definer.define<QPen_ArcTo>(); definer.define<QPen_AddRect>(); definer.define<QPen_AddRoundedRect>(); definer.define<QPen_AddEllipse>(); definer.define<QPen_AddArc>(); definer.define<QPen_AddWedge>(); definer.define<QPen_AddAnnularWedge>(); definer.define<QPen_Draw>(); definer.define<QPen_FillAxialGradient>(); definer.define<QPen_FillRadialGradient>(); definer.define<QPen_StringAtPoint>(); definer.define<QPen_StringInRect>(); definer.define<QPen_DrawImage>(); definer.define<QPen_TileImage>(); } } // namespace QtCollider
23,046
C++
.cpp
652
30.184049
120
0.620084
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,804
stack_layout.cpp
supercollider_supercollider/QtCollider/layouts/stack_layout.cpp
/************************************************************************ * * Copyright 2012 Jakob Leben (jakob.leben@gmail.com) * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (qt-info@nokia.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "stack_layout.hpp" #include <QWidget> namespace QtCollider { StackLayout::StackLayout(): _index(-1), _mode(StackOne), _gotParent(false) {} StackLayout::~StackLayout() { qDeleteAll(_list); } int StackLayout::addWidget(QWidget* widget) { return insertWidget(_list.count(), widget); } int StackLayout::insertWidget(int index, QWidget* widget) { addChildWidget(widget); index = qMin(index, _list.count()); if (index < 0) index = _list.count(); QWidgetItem* wi = new QWidgetItem(widget); _list.insert(index, wi); invalidate(); if (_index < 0) { setCurrentIndex(index); } else { if (index <= _index) ++_index; if (_mode == StackOne) widget->hide(); widget->lower(); } return index; } QLayoutItem* StackLayout::itemAt(int index) const { return _list.value(index); } QLayoutItem* StackLayout::takeAt(int index) { if (index < 0 || index >= _list.size()) return 0; QLayoutItem* item = _list.takeAt(index); if (index == _index) { _index = -1; if (_list.count() > 0) { int newIndex = (index == _list.count()) ? index - 1 : index; setCurrentIndex(newIndex); } } else if (index < _index) { --_index; } // NOTE: Here, the Qt implementation hides item->widget() if it exists and is not being // deleted. We can't reproduce this, because we can't access private info on whether the // widget is being deleted. return item; } void StackLayout::setCurrentIndex(int index) { QWidget* prev = currentWidget(); QWidget* next = widget(index); if (!next || next == prev) return; _index = index; if (!parent()) return; bool reenableUpdates = false; QWidget* parent = parentWidget(); if (parent && parent->updatesEnabled()) { reenableUpdates = true; parent->setUpdatesEnabled(false); } QWidget* fw = parent ? parent->window()->focusWidget() : 0; if (prev) { prev->clearFocus(); if (_mode == StackOne) prev->hide(); } next->raise(); next->show(); // try to move focus onto the incoming widget if focus // was somewhere on the outgoing widget. if (parent) { if (fw && (prev && prev->isAncestorOf(fw))) { // focus was on old page // look for the best focus widget we can find if (QWidget* nfw = next->focusWidget()) nfw->setFocus(); else { // second best: first child widget in the focus chain QWidget* i = fw; while ((i = i->nextInFocusChain()) != fw) { if (((i->focusPolicy() & Qt::TabFocus) == Qt::TabFocus) && !i->focusProxy() && i->isVisibleTo(next) && i->isEnabled() && next->isAncestorOf(i)) { i->setFocus(); break; } } // third best: incoming widget if (i == fw) next->setFocus(); } } } if (reenableUpdates) parent->setUpdatesEnabled(true); if (_mode == StackOne) // expandingDirections() might have changed, so invalidate(): invalidate(); } int StackLayout::currentIndex() const { return _index; } void StackLayout::setCurrentWidget(QWidget* widget) { int index = indexOf(widget); if (index == -1) { qWarning("StackLayout::setCurrentWidget: Widget %p not contained in stack", widget); return; } setCurrentIndex(index); } QWidget* StackLayout::currentWidget() const { return _index >= 0 ? _list.at(_index)->widget() : 0; } QWidget* StackLayout::widget(int index) const { if (index < 0 || index >= _list.size()) return 0; return _list.at(index)->widget(); } int StackLayout::count() const { return _list.size(); } void StackLayout::addItem(QLayoutItem* item) { QWidget* widget = item->widget(); if (widget) { addWidget(widget); delete item; } else { qWarning("StackLayout::addItem: Only widgets can be added"); } } QSize StackLayout::sizeHint() const { QSize s(0, 0); switch (_mode) { case StackOne: if (_index >= 0) if (QWidget* w = _list.at(_index)->widget()) { if (w->sizePolicy().horizontalPolicy() != QSizePolicy::Ignored) s.setWidth(w->sizeHint().width()); if (w->sizePolicy().verticalPolicy() != QSizePolicy::Ignored) s.setHeight(w->sizeHint().height()); } break; case StackAll: { int n = _list.count(); for (int i = 0; i < n; ++i) if (QWidget* w = _list.at(i)->widget()) { QSize ws(w->sizeHint()); if (w->sizePolicy().horizontalPolicy() == QSizePolicy::Ignored) ws.setWidth(0); if (w->sizePolicy().verticalPolicy() == QSizePolicy::Ignored) ws.setHeight(0); s = s.expandedTo(ws); } break; } } return s; } static QSize smartMinSize(const QSize& sizeHint, const QSize& minSizeHint, const QSize& minSize, const QSize& maxSize, const QSizePolicy& sizePolicy) { QSize s(0, 0); if (sizePolicy.horizontalPolicy() != QSizePolicy::Ignored) { if (sizePolicy.horizontalPolicy() & QSizePolicy::ShrinkFlag) s.setWidth(minSizeHint.width()); else s.setWidth(qMax(sizeHint.width(), minSizeHint.width())); } if (sizePolicy.verticalPolicy() != QSizePolicy::Ignored) { if (sizePolicy.verticalPolicy() & QSizePolicy::ShrinkFlag) { s.setHeight(minSizeHint.height()); } else { s.setHeight(qMax(sizeHint.height(), minSizeHint.height())); } } s = s.boundedTo(maxSize); if (minSize.width() > 0) s.setWidth(minSize.width()); if (minSize.height() > 0) s.setHeight(minSize.height()); return s.expandedTo(QSize(0, 0)); } QSize StackLayout::minimumSize() const { QSize s(0, 0); switch (_mode) { case StackOne: if (_index >= 0) if (QWidget* w = _list.at(_index)->widget()) s = smartMinSize(w->sizeHint(), w->minimumSizeHint(), w->minimumSize(), w->maximumSize(), w->sizePolicy()); break; case StackAll: { int n = _list.count(); for (int i = 0; i < n; ++i) if (QWidget* w = _list.at(i)->widget()) s = s.expandedTo(smartMinSize(w->sizeHint(), w->minimumSizeHint(), w->minimumSize(), w->maximumSize(), w->sizePolicy())); break; } } return s; } Qt::Orientations StackLayout::expandingDirections() const { Qt::Orientations directions; switch (_mode) { case StackOne: directions = _index >= 0 ? _list.at(_index)->expandingDirections() : Qt::Orientations {}; break; case StackAll: { Qt::Orientations directions {}; int n = _list.count(); for (int i = 0; i < n; ++i) directions |= _list.at(i)->expandingDirections(); break; } } return directions; } void StackLayout::setGeometry(const QRect& rect) { switch (_mode) { case StackOne: if (QWidget* widget = currentWidget()) widget->setGeometry(rect); break; case StackAll: if (const int n = _list.count()) for (int i = 0; i < n; ++i) if (QWidget* widget = _list.at(i)->widget()) widget->setGeometry(rect); break; } } StackLayout::StackingMode StackLayout::stackingMode() const { return _mode; } void StackLayout::setStackingMode(StackingMode stackingMode) { if (_mode == stackingMode) return; _mode = stackingMode; if (!parent()) return; const int n = _list.count(); if (n == 0) return; switch (_mode) { case StackOne: { const int idx = currentIndex(); if (idx >= 0) for (int i = 0; i < n; ++i) if (QWidget* widget = _list.at(i)->widget()) widget->setVisible(i == idx); break; } case StackAll: { // Turn overlay on: Make sure all widgets are the same size QRect geometry; if (const QWidget* widget = currentWidget()) geometry = widget->geometry(); for (int i = 0; i < n; ++i) if (QWidget* widget = _list.at(i)->widget()) { if (!geometry.isNull()) widget->setGeometry(geometry); widget->setVisible(true); } } break; } invalidate(); } void StackLayout::invalidate() { QWidget* pw = parentWidget(); if (pw && !_gotParent) { _gotParent = true; const int n = _list.count(); if (n == 0) return; QWidget* cw = currentWidget(); switch (_mode) { case StackOne: { if (cw) for (int i = 0; i < n; ++i) if (QWidget* widget = _list.at(i)->widget()) widget->setVisible(widget == cw); break; } case StackAll: { for (int i = 0; i < n; ++i) if (QWidget* widget = _list.at(i)->widget()) widget->setVisible(true); break; } } // NOTE: re-order the widgets after setting visibility, since the latter // may affect the order itself (at least on Mac OS X) if (cw) { for (int i = 0; i < n; ++i) { QWidget* w = _list.at(i)->widget(); if (w && w != cw) w->lower(); } } } QLayout::invalidate(); } } // namespace QtCollider
11,043
C++
.cpp
314
26.789809
119
0.550881
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,805
layouts.cpp
supercollider_supercollider/QtCollider/layouts/layouts.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "layouts.hpp" QC_DECLARE_QOBJECT_FACTORY(QcHBoxLayout); QC_DECLARE_QOBJECT_FACTORY(QcVBoxLayout); QC_DECLARE_QOBJECT_FACTORY(QcGridLayout); QC_DECLARE_QOBJECT_FACTORY(QcStackLayout); void QcGridLayout::addItem(const QVariantList& data) { if (data.count() < 6) return; int row = data[1].toInt(); int column = data[2].toInt(); int rSpan = data[3].toInt(); int cSpan = data[4].toInt(); Qt::Alignment alignment = (Qt::Alignment)data[5].toInt(); QVariant varObject = data[0]; QWidget* w = varObject.value<QWidget*>(); if (w) { addWidget(w, row, column, rSpan, cSpan, alignment); return; } QLayout* l = varObject.value<QLayout*>(); if (l) { addLayout(l, row, column, rSpan, cSpan, alignment); return; } }
1,719
C++
.cpp
45
34.577778
74
0.642472
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,806
QcTreeWidget.cpp
supercollider_supercollider/QtCollider/widgets/QcTreeWidget.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcTreeWidget.h" #include "../QcWidgetFactory.h" #include <PyrKernel.h> #include <QKeyEvent> class QcTreeWidgetFactory : public QcWidgetFactory<QcTreeWidget> { void initialize(QWidgetProxy* p, QcTreeWidget* w) { p->setMouseEventWidget(w->viewport()); } }; QC_DECLARE_FACTORY(QcTreeWidget, QcTreeWidgetFactory); QcTreeWidget::QcTreeWidget() { setAttribute(Qt::WA_AcceptTouchEvents); // Forward signals to argument-less versions connectable from SC. connect(this, SIGNAL(itemActivated(QTreeWidgetItem*, int)), this, SIGNAL(action())); connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), this, SIGNAL(itemPressedAction())); connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SIGNAL(currentItemChanged())); connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(onExpanded(QTreeWidgetItem*))); connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(onCollapsed(QTreeWidgetItem*))); } QVariantList QcTreeWidget::columns() const { QVariantList varList; QTreeWidgetItem* header = headerItem(); if (header) { for (int i = 0; i < header->columnCount(); ++i) { varList << header->text(i); } } return varList; } void QcTreeWidget::setColumns(const QVariantList& varList) { int count = varList.size(); setColumnCount(count); QStringList labels; Q_FOREACH (const QVariant& var, varList) labels << var.toString(); setHeaderLabels(labels); } void QcTreeWidget::onExpanded(QTreeWidgetItem* item) { Q_EMIT(expanded(QcTreeWidget::Item::safePtr(item))); } void QcTreeWidget::onCollapsed(QTreeWidgetItem* item) { Q_EMIT(collapsed(QcTreeWidget::Item::safePtr(item))); } QcTreeWidget::ItemPtr QcTreeWidget::currentItem() const { QTreeWidgetItem* item = QTreeWidget::currentItem(); return QcTreeWidget::Item::safePtr(item); } void QcTreeWidget::setCurrentItem(const ItemPtr& item) { _emitAction = false; QTreeWidget::setCurrentItem(item); _emitAction = true; } QcTreeWidget::ItemPtr QcTreeWidget::item(const QcTreeWidget::ItemPtr& parent, int index) { QTreeWidgetItem* item = parent ? parent->child(index) : QTreeWidget::topLevelItem(index); return QcTreeWidget::Item::safePtr(item); } QcTreeWidget::ItemPtr QcTreeWidget::parentItem(const QcTreeWidget::ItemPtr& item) { if (!item) return QcTreeWidget::ItemPtr(); return QcTreeWidget::Item::safePtr(item->parent()); } int QcTreeWidget::indexOfItem(const QcTreeWidget::ItemPtr& item) { if (!item) return -1; QTreeWidgetItem* parent = item->parent(); if (parent) return parent->indexOfChild(item); else return indexOfTopLevelItem(item); } QcTreeWidget::ItemPtr QcTreeWidget::addItem(const QcTreeWidget::ItemPtr& parent, const QVariantList& varList) { QStringList strings; for (int i = 0; i < varList.count(); ++i) strings << varList[i].toString(); Item* item = new Item(strings); if (!parent) addTopLevelItem(item); else parent->addChild(item); return item->safePtr(); } QcTreeWidget::ItemPtr QcTreeWidget::insertItem(const QcTreeWidget::ItemPtr& parent, int index, const QVariantList& varList) { int itemCount = topLevelItemCount(); if (index < 0 || index > itemCount) return ItemPtr(); QStringList strings; for (int i = 0; i < varList.count(); ++i) strings << varList[i].toString(); Item* item = new Item(strings); if (!parent) insertTopLevelItem(index, item); else parent->insertChild(index, item); if (!item->treeWidget()) { delete item; return ItemPtr(); } return item->safePtr(); } void QcTreeWidget::removeItem(const QcTreeWidget::ItemPtr& item) { delete item.ptr(); } QVariantList QcTreeWidget::strings(const QcTreeWidget::ItemPtr& item) { QVariantList varList; if (!item) return varList; for (int i = 0; i < item->columnCount(); ++i) { varList << item->text(i); } return varList; } void QcTreeWidget::setText(const QcTreeWidget::ItemPtr& item, int column, const QString& text) { if (item) item->setText(column, text); } void QcTreeWidget::setColor(const QcTreeWidget::ItemPtr& item, int column, const QColor& color) { if (item) item->setBackground(column, color); } void QcTreeWidget::setTextColor(const QcTreeWidget::ItemPtr& item, int column, const QColor& color) { if (item) item->setData(column, Qt::ForegroundRole, color); } QWidget* QcTreeWidget::itemWidget(const QcTreeWidget::ItemPtr& item, int column) { return item ? QTreeWidget::itemWidget(item, column) : 0; } void QcTreeWidget::setItemWidget(const QcTreeWidget::ItemPtr& item, int column, QWidget* o) { if (!item) return; if (!o) return; QTreeWidget::setItemWidget(item, column, o); } void QcTreeWidget::removeItemWidget(const QcTreeWidget::ItemPtr& item, int column) { if (item) QTreeWidget::removeItemWidget(item, column); } void QcTreeWidget::sort(int column, bool descending) { sortItems(column, descending ? Qt::DescendingOrder : Qt::AscendingOrder); } int QcTreeWidget::columnWidth(int column) { if (column < 0 || column >= columnCount()) return -1; else return QTreeWidget::columnWidth(column); } void QcTreeWidget::setColumnWidth(int column, int width) { QTreeWidget::setColumnWidth(column, width); } void QcTreeWidget::keyPressEvent(QKeyEvent* e) { QTreeWidget::keyPressEvent(e); switch (e->key()) { case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_PageUp: case Qt::Key_PageDown: case Qt::Key_Home: case Qt::Key_End: // Prevent propagating to parent when scroller reaches minimum or maximum: e->accept(); default: break; } } //////////////////////////////// Item ////////////////////////////////////// QcTreeWidget::ItemPtr QcTreeWidget::Item::safePtr(QTreeWidgetItem* item) { if (item && item->type() == Item::Type) return static_cast<Item*>(item)->safePtr(); else return ItemPtr(); } void QcTreeWidget::Item::initialize(VMGlobals* g, PyrObject* obj, const QcTreeWidget::ItemPtr& ptr) { Q_ASSERT(isKindOf(obj, SC_CLASS(TreeViewItem))); if (ptr.id()) { // store the SafePtr QcTreeWidget::ItemPtr* newPtr = new QcTreeWidget::ItemPtr(ptr); SetPtr(obj->slots + 0, newPtr); // store the id for equality comparison SetPtr(obj->slots + 1, ptr.id()); // install finalizer } else { SetNil(obj->slots + 0); SetNil(obj->slots + 1); } InstallFinalizer(g, obj, 2, &QcTreeWidget::Item::finalize); } int QcTreeWidget::Item::finalize(VMGlobals* g, PyrObject* obj) { qcDebugMsg(1, "finalizing QTreeViewItem!"); if (IsPtr(obj->slots + 0)) { QcTreeWidget::ItemPtr* ptr = static_cast<QcTreeWidget::ItemPtr*>(slotRawPtr(obj->slots + 0)); delete ptr; } return errNone; } bool QcTreeWidget::Item::operator<(const QTreeWidgetItem& other) const { int column = treeWidget()->sortColumn(); return text(column).toLower() < other.text(column).toLower(); }
8,238
C++
.cpp
211
34.232227
118
0.676858
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,807
QcScrollArea.cpp
supercollider_supercollider/QtCollider/widgets/QcScrollArea.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcScrollArea.h" #include "../QcWidgetFactory.h" #include <QLayout> #include <QScrollBar> #include <QEvent> #include <QChildEvent> #include <QApplication> class QcScrollWidgetFactory : public QcWidgetFactory<QcScrollWidget> { protected: virtual void initialize(QWidgetProxy* p, QcScrollWidget* w) { QObject::connect(w, SIGNAL(painting(QPainter*)), p, SLOT(customPaint(QPainter*))); } }; QC_DECLARE_FACTORY(QcScrollWidget, QcScrollWidgetFactory); QcScrollWidget::QcScrollWidget(QWidget* parent): QcCanvas(parent) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setAttribute(Qt::WA_AcceptTouchEvents); } QSize QcScrollWidget::sizeHint() const { QRect r = childrenRect(); QSize sz(r.x() + r.width(), r.y() + r.height()); return sz; } bool QcScrollWidget::event(QEvent* e) { int t = e->type(); if (t == QEvent::ChildAdded) { QChildEvent* ce = static_cast<QChildEvent*>(e); ce->child()->installEventFilter(this); } else if (t == QEvent::ChildRemoved) { updateGeometry(); } return QWidget::event(e); } bool QcScrollWidget::eventFilter(QObject* watched, QEvent* event) { Q_UNUSED(watched); switch (event->type()) { case QEvent::Resize: case QEvent::Move: case QEvent::Show: case QEvent::Hide: updateGeometry(); break; default: return false; } return false; } QC_DECLARE_QWIDGET_FACTORY(QcScrollArea); QcScrollArea::QcScrollArea() { connect(horizontalScrollBar(), SIGNAL(actionTriggered(int)), this, SIGNAL(scrolled())); connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SIGNAL(scrolled())); } void QcScrollArea::setWidget(QWidget* widget) { QScrollArea::setWidget(widget); setWidgetResizable(true); } void QcScrollArea::addChild(QWidget* w) { if (widget()) w->setParent(widget()); } QRectF QcScrollArea::innerBounds() const { QSize vs = viewport()->size(); if (!widget()) return QRectF(0, 0, vs.width(), vs.height()); QSize cs = widget()->size(); return QRectF(0, 0, qMax(vs.width(), cs.width()), qMax(vs.height(), cs.height())); } void QcScrollArea::setHasBorder(bool b) { if (b) QFrame::setFrameShape(QFrame::StyledPanel); else QFrame::setFrameShape(QFrame::NoFrame); } QPointF QcScrollArea::visibleOrigin() const { QWidget* w = widget(); return (w != 0 ? widget()->mapFromParent(QPoint(0, 0)) : QPoint(0, 0)); } void QcScrollArea::setVisibleOrigin(const QPointF& pt) { if (horizontalScrollBar()->maximum() < pt.x()) horizontalScrollBar()->setMaximum(pt.x()); if (verticalScrollBar()->maximum() < pt.y()) verticalScrollBar()->setMaximum(pt.y()); horizontalScrollBar()->setValue(pt.x()); verticalScrollBar()->setValue(pt.y()); }
3,749
C++
.cpp
105
31.885714
91
0.670715
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,808
QcButton.cpp
supercollider_supercollider/QtCollider/widgets/QcButton.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcButton.h" #include "../QcWidgetFactory.h" #include <QStylePainter> #include <QStyle> QC_DECLARE_QWIDGET_FACTORY(QcButton); QcButton::QcButton(): QtCollider::Style::Client(this), currentState(0) { setAttribute(Qt::WA_AcceptTouchEvents); connect(this, SIGNAL(clicked()), this, SLOT(doAction())); } void QcButton::setStates(const QVariantList& statesArg) { if (!statesArg.count()) return; states.clear(); Q_FOREACH (const QVariant& var, statesArg) { QVariantList stateArg = var.toList(); int count = stateArg.size(); State state; if (count >= 1) state.text = stateArg[0].toString(); if (count >= 2) state.textColor = stateArg[1].value<QColor>(); if (count >= 3) state.buttonColor = stateArg[2].value<QColor>(); states.append(state); } setState(0); } void QcButton::setState(int i) { int c = states.count(); if (!c) return; currentState = qBound(0, i, c - 1); setText(states[currentState].text); update(); } void QcButton::cycleStates() { if (states.size() < 2) return; int i = currentState + 1; if (i >= states.size()) i = 0; setState(i); } void QcButton::doAction() { cycleStates(); Q_EMIT(action((int)QApplication::keyboardModifiers())); } void QcButton::paintEvent(QPaintEvent* e) { using namespace QtCollider::Style; using QtCollider::Style::RoundRect; QStylePainter sp(this); QPalette plt(palette()); State state; if (states.count()) state = states[currentState]; if (state.textColor.isValid()) plt.setColor(QPalette::ButtonText, state.textColor); if (state.buttonColor.isValid()) plt.setColor(QPalette::Button, state.buttonColor); QStyleOptionButton option; initStyleOption(&option); QStyleOptionButton mbiOption = option; QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); bool sunken = isDown(); int radius = 2; bool hasMenu = (option.features & QStyleOptionButton::HasMenu); int mbiSize = hasMenu ? sp.style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &option, this) : 0; if (sunken) { plt.setColor(QPalette::ButtonText, plt.color(QPalette::ButtonText).darker(120)); option.rect.translate(1, 1); } option.palette = plt; QColor focusClr(hasFocus() ? focusColor() : QColor()); QRect r(rect()); RoundRect frame(r, radius); if (sunken) drawSunken(&p, plt, frame, plt.color(QPalette::Button), focusClr); else drawRaised(&p, plt, frame, plt.color(QPalette::Button), focusClr); p.setPen(plt.color(QPalette::ButtonText)); option.rect.adjust(0, 0, -mbiSize, 0); sp.drawControl(QStyle::CE_PushButtonLabel, option); if (hasMenu) { mbiOption.rect = QRect(r.right() - mbiSize + 2, r.height() / 2 - mbiSize / 2 + 3, mbiSize - 6, mbiSize - 6); sp.style()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &mbiOption, &p, this); } } void QcButton::setQcMenu(QcMenu* menu) { QPushButton::setMenu(menu); } QcMenu* QcButton::qcmenu() const { QMenu* menu = QPushButton::menu(); QcMenu* qcmenu = qobject_cast<QcMenu*>(menu); return qcmenu; } void QcButton::setIcon(const QtCollider::SharedImage& image) { if (image) { QIcon icon = QIcon(image->pixmap()); QAbstractButton::setIcon(icon); } else { QAbstractButton::setIcon(QIcon()); } }
4,423
C++
.cpp
122
31.278689
116
0.648326
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,809
QcTextEdit.cpp
supercollider_supercollider/QtCollider/widgets/QcTextEdit.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcTextEdit.h" #include "../QcWidgetFactory.h" #include "../hacks/hacks_qt.hpp" #include <QFile> #include <QUrl> #include <QKeyEvent> #include <QApplication> #include <QTextBlock> class QcTextEditFactory : public QcWidgetFactory<QcTextEdit> { void initialize(QWidgetProxy* p, QcTextEdit* w) { p->setMouseEventWidget(w->viewport()); } }; QC_DECLARE_FACTORY(QcTextEdit, QcTextEditFactory); QcTextEdit::QcTextEdit(): _interpretSelection(true) { setAttribute(Qt::WA_AcceptTouchEvents); connect(this, SIGNAL(interpret(QString)), qApp, SLOT(interpret(QString)), Qt::QueuedConnection); } QString QcTextEdit::documentFilename() const { return _document; } void QcTextEdit::setDocument(const QString& filename) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QByteArray data = file.readAll(); setText(data); _document = filename; } int QcTextEdit::selectionStart() const { return textCursor().selectionStart(); } int QcTextEdit::selectionSize() const { QTextCursor cursor = textCursor(); return cursor.selectionEnd() - cursor.selectionStart(); } void QcTextEdit::select(int start, int size) { if (start < 0) start = 0; QTextCursor cursor(document()); cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, start); cursor.movePosition(size > 0 ? QTextCursor::Right : QTextCursor::Left, QTextCursor::KeepAnchor, qAbs(size)); setTextCursor(cursor); } QString QcTextEdit::selectedString() const { QString selection(textCursor().selectedText()); return prepareText(selection); } void QcTextEdit::replaceSelectedText(const QString& string) { QTextCursor cursor(textCursor()); if (cursor.hasSelection()) { cursor.removeSelectedText(); }; cursor.insertText(string); } QString QcTextEdit::currentLine() const { return textCursor().block().text(); } void QcTextEdit::setTextFont(const QFont& f) { QTextCharFormat format; format.setFont(f); QTextCursor cursor(document()); cursor.select(QTextCursor::Document); cursor.mergeCharFormat(format); QTextEdit::setFont(f); } void QcTextEdit::setTextColor(const QColor& color) { QTextCharFormat format; format.setForeground(color); QTextCursor cursor(document()); cursor.select(QTextCursor::Document); cursor.mergeCharFormat(format); } void QcTextEdit::setRangeColor(const QVariantList& list) { if (list.count() < 3) return; QColor c = list[0].value<QColor>(); int start = list[1].toInt(); int size = list[2].toInt(); QTextCharFormat format; format.setForeground(c); QTextCursor cursor(document()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, start); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, size); cursor.mergeCharFormat(format); } void QcTextEdit::setRangeFont(const QVariantList& list) { if (list.count() < 3) return; QFont f = list[0].value<QFont>(); int start = list[1].toInt(); int size = list[2].toInt(); QTextCharFormat format; format.setFont(f); QTextCursor cursor(document()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, start); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, size); cursor.mergeCharFormat(format); } void QcTextEdit::setRangeText(const QVariantList& list) { if (list.count() < 3) return; QString text = list[0].value<QString>(); int start = list[1].toInt(); int size = list[2].toInt(); QTextCursor cursor(document()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, start); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, size); cursor.insertText(text); } void QcTextEdit::keyPressEvent(QKeyEvent* e) { if (_interpretSelection && e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier) && (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter)) { QTextCursor c(textCursor()); QString code; if (c.hasSelection()) code = c.selectedText(); else code = c.block().text(); Q_EMIT(interpret(prepareText(code))); return; } QTextEdit::keyPressEvent(e); } void QcTextEdit::insertFromMimeData(const QMimeData* data) { if (data->hasUrls()) { QTextCursor c(textCursor()); QList<QUrl> urls = data->urls(); int n = urls.count(); for (int i = 0; i < n; ++i) { QUrl& url = urls[i]; QString text = QURL_IS_LOCAL_FILE(url) ? url.toLocalFile() : url.toString(); c.insertText(text); if (n > 1) c.insertText("\n"); } } else QTextEdit::insertFromMimeData(data); } QString& QcTextEdit::prepareText(QString& text) const { // NOTE: QTextDocument contains unicode paragraph separators U+2029 // instead of newline \n characters return text.replace(QChar(0x2029), QChar('\n')); }
5,993
C++
.cpp
156
33.769231
112
0.683911
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,810
QcMenu.cpp
supercollider_supercollider/QtCollider/widgets/QcMenu.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcMenu.h" #include "../QcWidgetFactory.h" #include <PyrKernel.h> #include <QKeyEvent> QC_DECLARE_QWIDGET_FACTORY(QcMenu); QC_DECLARE_QWIDGET_FACTORY(QcToolBar); QC_DECLARE_QOBJECT_FACTORY(QcAction); QC_DECLARE_QOBJECT_FACTORY(QcWidgetAction); QcMenu::QcMenu(): QMenu(NULL) { setAttribute(Qt::WA_DeleteOnClose, false); } void QcMenu::popup(QPointF pos, QAction* action) { QMenu::popup(QPoint(pos.x(), pos.y()), action); } void QcMenu::addAction(QAction* action) { if (action) { QMenu::addAction(action); } else { QMenu::addSeparator(); } } void QcMenu::insertAction(QAction* beforeAction, QAction* action) { if (action) { QMenu::insertAction(beforeAction, action); } else { QMenu::insertSeparator(beforeAction); } } void QcMenu::removeAction(QAction* action) { if (action) { QMenu::removeAction(action); } } void QcToolBar::addAction(QAction* action) { if (action) { QToolBar::addAction(action); } else { QToolBar::addSeparator(); } } void QcToolBar::insertAction(QAction* beforeAction, QAction* action) { if (action) { QToolBar::insertAction(beforeAction, action); } else { QToolBar::insertSeparator(beforeAction); } } void QcToolBar::removeAction(QAction* action) { if (action) { QToolBar::removeAction(action); } } QcAction::QcAction(): QAction(NULL) {} QcWidgetAction::QcWidgetAction(): QWidgetAction(NULL) {} void QcAction::setIcon(const QtCollider::SharedImage& image) { if (image) { QIcon icon(image->pixmap()); QAction::setIcon(icon); } else { QAction::setIcon(QIcon()); } } QcToolBar::QcToolBar(): QToolBar() {}
2,638
C++
.cpp
79
29.670886
100
0.66339
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,811
QcWebView.cpp
supercollider_supercollider/QtCollider/widgets/QcWebView.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #ifdef SC_USE_QTWEBENGINE # include "QcWebView.h" # include "../widgets/web_page.hpp" # include <QWebEnginePage> # include <QWebEngineSettings> # include <QAction> # include <QMenu> # include <QShortcut> # include <QKeyEvent> # include <QApplication> # include <QStyle> # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) # include <QWebEngineCallback> # include <QWebEngineContextMenuData> # else # include <QWebEngineContextMenuRequest> # include <QWebEngineView> # include <QWebEngineFindTextResult> # endif namespace QtCollider { WebView::WebView(QWidget* parent): QWebEngineView(parent), _editable(false) { QtCollider::WebPage* page = new WebPage(this); setPage(page); connectPage(page); // Set the style's standard palette to avoid system's palette incoherencies // get in the way of rendering web pages setPalette(style()->standardPalette()); setAttribute(Qt::WA_AcceptTouchEvents); page->action(QWebEnginePage::Copy)->setShortcut(QKeySequence::Copy); page->action(QWebEnginePage::Paste)->setShortcut(QKeySequence::Paste); page->action(QWebEnginePage::Reload)->setShortcut(QKeySequence::Refresh); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool))); } void WebView::connectPage(QtCollider::WebPage* page) { connect(page, SIGNAL(jsConsoleMsg(const QString&, int, const QString&)), this, SIGNAL(jsConsoleMsg(const QString&, int, const QString&))); connect(page, SIGNAL(linkHovered(const QString&)), this, SIGNAL(linkHovered(const QString&))); connect(page, SIGNAL(geometryChangeRequested(const QRect&)), this, SIGNAL(geometryChangeRequested(const QRect&))); connect(page, SIGNAL(windowCloseRequested()), this, SIGNAL(windowCloseRequested())); connect(page, SIGNAL(scrollPositionChanged(const QPointF&)), this, SIGNAL(scrollPositionChanged(const QPointF&))); connect(page, SIGNAL(contentsSizeChanged(const QSizeF&)), this, SIGNAL(contentsSizeChanged(const QSizeF&))); connect(page, SIGNAL(audioMutedChanged(bool)), this, SIGNAL(audioMutedChanged(bool))); connect(page, SIGNAL(recentlyAudibleChanged(bool)), this, SIGNAL(recentlyAudibleChanged(bool))); connect(page, SIGNAL(navigationRequested(QUrl, QWebEnginePage::NavigationType, bool)), this, SLOT(onLinkClicked(QUrl, QWebEnginePage::NavigationType, bool))); connect(page->action(QWebEnginePage::Reload), SIGNAL(triggered(bool)), this, SLOT(onPageReload())); connect(page, &WebPage::renderProcessTerminated, this, &WebView::onRenderProcessTerminated); } void WebView::onRenderProcessTerminated(QWebEnginePage::RenderProcessTerminationStatus status, int code) { Q_EMIT(renderProcessTerminated((int)status, code)); } void WebView::triggerPageAction(int action, bool checked) { QWebEngineView::triggerPageAction((QWebEnginePage::WebAction)action, checked); } QString WebView::url() const { return QWebEngineView::url().toString(); } void WebView::setUrl(const QString& str) { load(urlFromString(str)); } bool WebView::delegateReload() const { WebPage* p = qobject_cast<QtCollider::WebPage*>(page()); Q_ASSERT(p); return p->delegateReload(); } void WebView::setDelegateReload(bool flag) { WebPage* p = qobject_cast<QtCollider::WebPage*>(page()); Q_ASSERT(p); p->setDelegateReload(flag); } void WebView::setFontFamily(int generic, const QString& specific) { settings()->setFontFamily((QWebEngineSettings::FontFamily)generic, specific); } QAction* WebView::pageAction(QWebEnginePage::WebAction action) const { return QWebEngineView::pageAction(action); } void WebView::setHtml(const QString& html, const QString& baseUrl) { if (page()) { page()->setHtml(html, baseUrl); } } void WebView::setContent(const QVector<int>& data, const QString& mimeType, const QString& baseUrl) { if (page()) { QByteArray byteData; for (int val : data) { byteData.push_back((char)val); } page()->setContent(byteData, mimeType, baseUrl); } } void WebView::toHtml(QcCallback* cb) const { if (page()) { if (cb) { page()->toHtml(cb->asFunctor()); } else { page()->toHtml([](const QString&) {}); } } else { cb->asFunctor()(QString()); } } void WebView::toPlainText(QcCallback* cb) const { if (page()) { if (cb) { page()->toPlainText(cb->asFunctor()); } else { page()->toPlainText([](const QString&) {}); } } else { cb->asFunctor()(QString()); } } void WebView::runJavaScript(const QString& script, QcCallback* cb) { if (page()) { if (cb) { page()->runJavaScript(script, cb->asFunctor()); } else { page()->runJavaScript(script, [](const QVariant&) {}); } } else { cb->asFunctor()(QString()); } } void WebView::setWebAttribute(int attr, bool on) { if (page()) { page()->settings()->setAttribute((QWebEngineSettings::WebAttribute)attr, on); } } bool WebView::testWebAttribute(int attr) { return page() ? page()->settings()->testAttribute((QWebEngineSettings::WebAttribute)attr) : false; } void WebView::resetWebAttribute(int attr) { if (page()) { page()->settings()->resetAttribute((QWebEngineSettings::WebAttribute)attr); } } void WebView::navigate(const QString& urlString) { QUrl url(urlString); this->load(url); } void WebView::findText(const QString& searchText, bool reversed, QcCallback* cb) { QWebEnginePage::FindFlags flags; if (reversed) flags |= QWebEnginePage::FindBackward; if (!cb) { QWebEngineView::findText(searchText, flags); } else { # if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QWebEngineView::findText(searchText, flags, cb->asFunctor()); # else QWebEngineView::findText(searchText, flags, [cb](const QWebEngineFindTextResult& result) { cb->asFunctor()(result.numberOfMatches() > 0); }); # endif } } void WebView::onPageReload() { Q_EMIT(reloadTriggered(url())); } void WebView::contextMenuEvent(QContextMenuEvent* event) { QMenu menu; # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) const QWebEngineContextMenuData& contextData = page()->contextMenuData(); if (!contextData.linkUrl().isEmpty()) { # else auto contextData = this->lastContextMenuRequest(); if (!contextData->linkUrl().isEmpty()) { # endif menu.addAction(pageAction(QWebEnginePage::CopyLinkToClipboard)); menu.addSeparator(); } # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) if (contextData.isContentEditable() || !contextData.selectedText().isEmpty()) { # else if (contextData->isContentEditable() || !contextData->selectedText().isEmpty()) { # endif menu.addAction(pageAction(QWebEnginePage::Copy)); # if (QT_VERSION < QT_VERSION_CHECK(6, 2, 0)) if (contextData.isContentEditable()) # else if (contextData->isContentEditable()) # endif menu.addAction(pageAction(QWebEnginePage::Paste)); menu.addSeparator(); } menu.addAction(pageAction(QWebEnginePage::Back)); menu.addAction(pageAction(QWebEnginePage::Forward)); menu.addAction(pageAction(QWebEnginePage::Reload)); menu.exec(event->globalPos()); } // webView's renderer keypresses don't arrive to webView // duplicate them bool WebView::eventFilter(QObject* obj, QEvent* event) { if (event->type() == QEvent::KeyPress) { // takes ownership of newEvent # if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) auto newEvent = new QKeyEvent(*static_cast<QKeyEvent*>(event)); # else auto newEvent = static_cast<QKeyEvent*>(event->clone()); # endif QApplication::postEvent(this, newEvent); } event->ignore(); return false; } // stop keypresses here to avoid duplicates in parents bool WebView::event(QEvent* ev) { if (ev->type() == QEvent::KeyPress) return true; return QWebEngineView::event(ev); } void WebView::pageLoaded(bool ok) { this->focusProxy()->installEventFilter(this); } void WebView::setEditable(bool b) { _editable = b; if (_editable) { page()->runJavaScript("document.documentElement.contentEditable = true"); } else { page()->runJavaScript("document.documentElement.contentEditable = false"); } } bool WebView::overrideNavigation() const { WebPage* p = qobject_cast<WebPage*>(page()); return p ? p->delegateNavigation() : false; } void WebView::setOverrideNavigation(bool b) { WebPage* p = qobject_cast<WebPage*>(page()); if (p) { p->setDelegateNavigation(b); } } void WebView::onLinkClicked(const QUrl& url, QWebEnginePage::NavigationType type, bool isMainFrame) { Q_EMIT(navigationRequested(url, (int)type, isMainFrame)); } } // namespace QtCollider #endif // SC_USE_QTWEBENGINE
9,916
C++
.cpp
247
35.696356
118
0.681856
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,812
QcPopUpMenu.cpp
supercollider_supercollider/QtCollider/widgets/QcPopUpMenu.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcPopUpMenu.h" #include "../QcWidgetFactory.h" QC_DECLARE_QWIDGET_FACTORY(QcPopUpMenu); QcPopUpMenu::QcPopUpMenu(): _changed(false), _reactivation(false) { connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(setChanged())); connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(clearChanged()), Qt::QueuedConnection); connect(this, SIGNAL(activated(int)), this, SLOT(doAction(int))); } void QcPopUpMenu::setItems(const QVariantList& items) { clear(); Q_FOREACH (const QVariant& item, items) addItem(item.toString()); } void QcPopUpMenu::doAction(int choice) { if (_changed || _reactivation) Q_EMIT(action()); }
1,591
C++
.cpp
37
40.243243
102
0.669897
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,813
QcScope.cpp
supercollider_supercollider/QtCollider/widgets/QcScope.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcScope.h" #include "../QcWidgetFactory.h" #include <QPainter> #include <QTimer> QC_DECLARE_QWIDGET_FACTORY(QcScope); QcScope::QcScope(): bufNum(0), xOffset(0.f), yOffset(0.f), xZoom(1.f), yZoom(1.f), style(0), _bkg(QColor(0, 0, 0)) { memset(&buffer, 0, sizeof(SndBuf)); timer = new QTimer(this); timer->setInterval(15); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); connect(timer, SIGNAL(timeout()), this, SLOT(updateScope())); } QcScope::~QcScope() { free(buffer.data); } void QcScope::setBufferNumber(int n) { bufNum = n; timer->start(); } void QcScope::setWaveColors(const QVariantList& newColors) { colors.clear(); Q_FOREACH (const QVariant& var, newColors) { QColor color = var.value<QColor>(); if (!color.isValid()) colors.append(QColor(0, 0, 0)); else colors.append(color); } } int QcScope::updateInterval() const { return timer->interval(); } void QcScope::setUpdateInterval(int interval) { timer->setInterval(qMax(0, interval)); } int getScopeBuf(uint32 index, SndBuf* buf, bool& changed); void QcScope::updateScope() { #ifndef NO_INTERNAL_SERVER // printf("update\n"); bool changed; getScopeBuf(bufNum, &buffer, changed); if (changed) { // printf("channels: %i\n", buffer.channels); update(); } #endif } inline void QcScope::setPoint(QPointF& pt, float x, float y, float xRatio, float yRatio, int xStart, int yStart) { pt.setX(((x + xOffset) * xRatio) + xStart); pt.setY(yStart - ((y + yOffset) * yRatio)); } void QcScope::paint1D(bool overlapped, QPainter& p) { QRect area = rect(); float xRatio = xZoom * area.width() / (float)buffer.frames; float yRatio = yZoom * area.height() * 0.5; if (!overlapped) yRatio /= buffer.channels; int c, f, s; QPointF pt1; QPointF pt2; QPen pen; pen.setWidth(0); // width==0 means width 1 regardless of transformations for (c = 0; c < buffer.channels; c++) { pen.setColor(c < colors.count() ? colors[c] : QColor(255, 255, 255)); p.setPen(pen); float yCenter = area.height() * 0.5; if (!overlapped) { yCenter *= (c * 2 + 1); yCenter /= buffer.channels; } yCenter += area.y(); setPoint(pt1, 0, buffer.data[c], xRatio, yRatio, area.x(), yCenter); for (f = 1, s = c + buffer.channels; f < buffer.frames; f++, s += buffer.channels) { setPoint(pt2, f, buffer.data[s], xRatio, yRatio, area.x(), yCenter); p.drawLine(pt1, pt2); pt1 = pt2; } } } void QcScope::paint2D(QPainter& p) { QPen pen; pen.setWidth(0); // width==0 means width 1 regardless of transformations pen.setColor(colors.count() ? colors[0] : QColor(255, 255, 255)); QRect area = rect(); int minSize = qMin(area.width(), area.height()); float xRatio = xZoom * minSize * 0.5; float yRatio = yZoom * minSize * 0.5; QPoint center = area.center(); int centerY = center.y(); int centerX = center.x(); QPointF pt1; QPointF pt2; float* data = buffer.data; float y = buffer.channels > 1 ? data[1] : 0.f; setPoint(pt1, data[0], y, xRatio, yRatio, centerX, centerY); data += buffer.channels; int f; for (f = 1; f < buffer.frames; f++, data += buffer.channels) { if (buffer.channels > 1) y = data[1]; setPoint(pt2, data[0], y, xRatio, yRatio, centerX, centerY); p.drawLine(pt1, pt2); pt1 = pt2; } } void QcScope::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QPainter p(this); QRect area = rect(); p.fillRect(area, _bkg); if (buffer.frames == 0) return; if (style == 0) paint1D(false, p); else if (style == 1) paint1D(true, p); else if (style == 2) paint2D(p); }
4,824
C++
.cpp
133
31.165414
116
0.615566
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,814
BasicWidgets.cpp
supercollider_supercollider/QtCollider/widgets/BasicWidgets.cpp
/************************************************************************ * * Copyright 2010 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "BasicWidgets.h" #include "../QcWidgetFactory.h" #include <QPaintEvent> #include <QPainter> QC_DECLARE_QWIDGET_FACTORY(QcDefaultWidget); QC_DECLARE_QWIDGET_FACTORY(QcHLayoutWidget); QC_DECLARE_QWIDGET_FACTORY(QcVLayoutWidget); void QcSimpleWidget::setBackground(const QColor& c) { if (_bkg == c) return; _bkg = c; setAttribute(Qt::WA_OpaquePaintEvent, c.isValid() && c.alpha() == 255); update(); } void QcSimpleWidget::setBackgroundImage(const QtCollider::SharedImage& image, const QRectF& rect, int tileMode, double opacity) { _bkg_image.setImage(image, rect, tileMode, opacity); update(); } void QcSimpleWidget::paintEvent(QPaintEvent* e) { QPainter painter(this); if (_bkg.isValid()) painter.fillRect(e->rect(), _bkg); if (_bkg_image.isValid()) _bkg_image.paint(&painter, rect()); } class QcCustomPaintedFactory : public QcWidgetFactory<QcCustomPainted> { protected: virtual void initialize(QWidgetProxy* p, QcCustomPainted* w) { QObject::connect(w, SIGNAL(painting(QPainter*)), p, SLOT(customPaint(QPainter*))); } }; QC_DECLARE_FACTORY(QcCustomPainted, QcCustomPaintedFactory);
2,125
C++
.cpp
53
36.339623
111
0.673459
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,815
QcKnob.cpp
supercollider_supercollider/QtCollider/widgets/QcKnob.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcKnob.hpp" #include "../QcWidgetFactory.h" #include "../style/routines.hpp" #include <QMouseEvent> #include <QPainter> using namespace QtCollider; QC_DECLARE_QWIDGET_FACTORY(QcKnob); QcKnob::QcKnob(): Style::Client(this), _value(0.f), _step(0.01), _mode(0), _centered(false) { setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setAttribute(Qt::WA_AcceptTouchEvents); } void QcKnob::setValue(double val) { _value = qBound(0.0, val, 1.0); update(); } void QcKnob::mousePressEvent(QMouseEvent* e) { if (_mode == 0) { setValue(value(e->pos())); Q_EMIT(action()); } _prevPos = e->pos(); } void QcKnob::mouseMoveEvent(QMouseEvent* e) { if (!e->buttons()) return; if (_mode == 0) { double val = value(e->pos()); if (!(val < 0.0 && _value > 0.5) && !(val > 1.0 && _value < 0.5)) setValue(value(e->pos())); Q_EMIT(action()); } else { int dif; dif = _mode == 1 ? e->pos().x() - _prevPos.x() : _prevPos.y() - e->pos().y(); if (dif != 0) { double step = _step; modifyStep(&step); setValue(_value + dif * step); Q_EMIT(action()); } } _prevPos = e->pos(); } void QcKnob::paintEvent(QPaintEvent*) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); const QPalette& plt(palette()); QColor cGroove = plt.color(QPalette::Window).lighter(115); QColor cVal = plt.color(QPalette::ButtonText); QRect bounds(rect()); int sz = qMin(bounds.width(), bounds.height()); float sz_2 = sz * 0.5f; QPointF center = QRectF(bounds).center(); p.translate(center); double rad = sz_2 * 0.75; Ellipse shKnob(QRectF(-rad, -rad, rad * 2, rad * 2)); drawRaised(&p, plt, shKnob, plt.color(QPalette::Button).lighter(105), hasFocus() ? focusColor() : QColor()); p.scale(sz_2, sz_2); QPen pen; pen.setWidthF(0.1); p.setBrush(Qt::NoBrush); QRectF r(-0.95, -0.95, 1.9, 1.9); p.save(); // groove & value indicator rotation double range = 300.0; p.rotate(-90 - range * 0.5); double valAng = -_value * range; if (_centered) { double min = qMin(valAng, -range * 0.5); double max = qMax(valAng, -range * 0.5); pen.setColor(cGroove); p.setPen(pen); p.drawArc(r, -range * 16.f, (min + range) * 16.f); p.drawArc(r, max * 16.f, -max * 16.f); pen.setColor(plt.color(QPalette::WindowText)); p.setPen(pen); p.drawArc(r, min * 16.f, (max - min) * 16.f); } else { pen.setColor(cGroove); p.setPen(pen); p.drawArc(r, -range * 16.f, (valAng + range) * 16.f); pen.setColor(plt.color(QPalette::WindowText)); p.setPen(pen); p.drawArc(r, valAng * 16.f, -valAng * 16.f); } p.restore(); // groove & value indicator rotation p.rotate((360.0 - range) * 0.5 - valAng); QLineF line(0, 0.05, 0, 0.55); pen.setColor(cVal); pen.setWidthF(0.15); pen.setCapStyle(Qt::RoundCap); p.setPen(pen); p.drawLine(line); } double QcKnob::value(const QPoint& pt) { double angle = QLineF(rect().center(), pt).angle(); if (angle > 270.0) angle -= 270.0; else angle += 90; return (330 - angle) / 300.0; }
4,376
C++
.cpp
123
30.235772
112
0.594031
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,816
web_page.cpp
supercollider_supercollider/QtCollider/widgets/web_page.cpp
/************************************************************************ * * Copyright 2011-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #ifdef SC_USE_QTWEBENGINE # include "web_page.hpp" # include <QApplication> # include <QClipboard> namespace QtCollider { void WebPage::triggerAction(WebAction action, bool checked) { switch (action) { case QWebEnginePage::Reload: if (_delegateReload) return; break; case QWebEnginePage::Copy: // ignore text formatting, copy only plain text: QApplication::clipboard()->setText(selectedText()); return; default: break; } QWebEnginePage::triggerAction(action, checked); } void WebPage::javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level, const QString& message, int lineNumber, const QString& sourceID) { Q_EMIT(jsConsoleMsg(message, lineNumber, sourceID)); } bool WebPage::acceptNavigationRequest(const QUrl& url, QWebEnginePage::NavigationType type, bool isMainFrame) { if (type == QWebEnginePage::NavigationTypeLinkClicked) { Q_EMIT(navigationRequested(url, type, isMainFrame)); if (_delegateNavigation) { return false; } } return QWebEnginePage::acceptNavigationRequest(url, type, isMainFrame); } } // namespace QtCollider #endif // SC_USE_QTWEBENGINE
2,172
C++
.cpp
55
34.763636
115
0.666192
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,817
QcPenPrinter.cpp
supercollider_supercollider/QtCollider/widgets/QcPenPrinter.cpp
/************************************************************************ * * Copyright 2011 Jonatan Liljedahl <lijon@kymatica.com> * Copyright 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcPenPrinter.h" #include "../QcObjectFactory.h" QC_DECLARE_QOBJECT_FACTORY(QcPenPrinter);
1,066
C++
.cpp
24
42.5
74
0.657692
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,818
QcFileDialog.cpp
supercollider_supercollider/QtCollider/widgets/QcFileDialog.cpp
/************************************************************************ * * Copyright 2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcFileDialog.h" #include "../QcObjectFactory.h" QC_DECLARE_QOBJECT_FACTORY(QcFileDialog); QcFileDialog::QcFileDialog(int fileMode, int acceptMode, const QString& startDir) { dialog = new QFileDialog(); dialog->setDirectory(QDir { startDir }); switch (fileMode) { case QFileDialog::AnyFile: dialog->setFileMode(QFileDialog::AnyFile); break; case QFileDialog::ExistingFile: dialog->setFileMode(QFileDialog::ExistingFile); break; case QFileDialog::Directory: dialog->setFileMode(QFileDialog::Directory); break; case QFileDialog::ExistingFiles: dialog->setFileMode(QFileDialog::ExistingFiles); break; default: qcErrorMsg("File dialog created with invalid file mode!\n"); } switch (acceptMode) { case QFileDialog::AcceptOpen: dialog->setAcceptMode(QFileDialog::AcceptOpen); break; case QFileDialog::AcceptSave: dialog->setAcceptMode(QFileDialog::AcceptSave); break; default: qcErrorMsg("File dialog created with invalid accept mode!\n"); } setParent(dialog); connect(dialog, SIGNAL(finished(int)), this, SLOT(onFinished(int))); }
2,126
C++
.cpp
55
33.963636
83
0.667475
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,819
QcMultiSlider.cpp
supercollider_supercollider/QtCollider/widgets/QcMultiSlider.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcMultiSlider.h" #include "../QcWidgetFactory.h" #include "../style/routines.hpp" #include <QApplication> #include <QMouseEvent> #include <QPainter> #include <QPainterPath> #include <cmath> QC_DECLARE_QWIDGET_FACTORY(QcMultiSlider); QcMultiSlider::QcMultiSlider(): QtCollider::Style::Client(this), _currentIndex(0), _selectionSize(1), roundStep(0.f), editable(true), ort(Qt::Vertical), elastic(false), thumbSize(QSizeF(12.f, 12.f)), gap(1), drawRects(true), drawLines(false), isFilled(false), highlight(false), startIndex(0) { setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAttribute(Qt::WA_AcceptTouchEvents); connect(this, SIGNAL(modified()), this, SLOT(update())); connect(this, SIGNAL(interacted()), this, SLOT(doAction())); } void QcMultiSlider::setSliderCount(int newSize) { while (newSize > _values.size()) _values.append(0.f); while (newSize < _values.size()) _values.removeLast(); update(); } QVector<double> QcMultiSlider::values() const { return QVector<double>::fromList(_values); } void QcMultiSlider::setValues(const QVector<double>& vec) { _values.clear(); Q_FOREACH (double value, vec) _values << qBound(0.0, rounded(value), 1.0); update(); } double QcMultiSlider::value() const { if (_currentIndex >= 0 && _currentIndex < _values.count()) return _values[_currentIndex]; else return 0.0; } void QcMultiSlider::setValue(double val) { if (_currentIndex >= 0 && _currentIndex < _values.count()) setValue(_currentIndex, val); update(); } QVector<double> QcMultiSlider::reference() const { return QVector<double>::fromList(_ref); } void QcMultiSlider::setReference(const QVector<double>& vec) { _ref.clear(); Q_FOREACH (double value, vec) _ref << qBound(0.0, value, 1.0); update(); } void QcMultiSlider::setStep(double step) { if (roundStep == step) return; roundStep = step; if (step == 0.0) return; int c = _values.count(); int i; for (i = 0; i < c; ++i) setValue(i, _values[i]); update(); } void QcMultiSlider::setIndex(int i) { if (i >= 0 && i < _values.count()) { _currentIndex = i; _selectionSize = 1; update(); } } void QcMultiSlider::setSelectionSize(int i) { _selectionSize = qMin(i, _values.count() - _currentIndex); update(); } inline void QcMultiSlider::setValue(int index, double value) { _values[index] = qBound(0.0, rounded(value), 1.0); } inline double QcMultiSlider::rounded(double value) { return roundStep > 0.0 ? qRound(value / roundStep) * roundStep : value; } QRect QcMultiSlider::contentsRect() { return QtCollider::Style::sunkenContentsRect(rect()).adjusted(2, 2, -2, -2); } QRect QcMultiSlider::valueRect(int count, qreal& spacing) { QRect r(contentsRect()); bool horiz = ort == Qt::Horizontal; spacing = elastic ? (qreal)(horiz ? r.height() : r.width()) / count : thumbSize.width() + gap; if (!isFilled) { int hnd = thumbSize.height(); if (horiz) { r.setWidth(r.width() - hnd); r.moveLeft(r.left() + hnd * 0.5); } else { r.setHeight(r.height() - hnd); r.moveTop(r.top() + hnd * 0.5); } } return r; } void QcMultiSlider::mousePressEvent(QMouseEvent* e) { using namespace QtCollider::Style; moveOrigin = e->pos(); int c = _values.count(); if (!c) return; bool horiz = ort == Qt::Horizontal; qreal spacing; QRect r(valueRect(c - startIndex, spacing)); int i; float val; if (horiz) { i = spacing > 0.f ? floor((float)(moveOrigin.y() - r.y()) / spacing) : 0; val = xValue((qreal)moveOrigin.x(), r); } else { i = spacing > 0.f ? floor((float)(moveOrigin.x() - r.x()) / spacing) : 0; val = yValue((qreal)moveOrigin.y(), r); } i += startIndex; if (i >= startIndex && i < c) { _currentIndex = i; _selectionSize = 1; if (editable) setValue(i, val); if (editable || highlight) Q_EMIT(modified()); Q_EMIT(interacted()); } } void QcMultiSlider::mouseMoveEvent(QMouseEvent* e) { using namespace QtCollider::Style; if (!e->buttons()) return; int c = _values.count(); QPoint pos = e->pos(); if (!c) { moveOrigin = pos; return; } qreal xStep; QRect r(valueRect(c - startIndex, xStep)); float xOrig, yOrig, xDest, yDest; int xOffset, xRange; int iOrig, iDest, iMax; if (ort == Qt::Vertical) { xOffset = r.left(); xRange = r.width(); xOrig = moveOrigin.x(); yOrig = yValue(moveOrigin.y(), r); xDest = pos.x(); yDest = yValue(pos.y(), r); } else { xOffset = r.top(); xRange = r.height(); xOrig = moveOrigin.y(); yOrig = xValue(moveOrigin.x(), r); xDest = pos.y(); yDest = xValue(pos.x(), r); } if (xStep > 0.0) { iOrig = floor((xOrig - xOffset) / xStep); iOrig += startIndex; iDest = floor((xDest - xOffset) / xStep); iDest += startIndex; iMax = elastic ? c : qMin(c, int((float)xRange / xStep) + startIndex + 1); } else { iOrig = iDest = iMax = startIndex; } if (editable && (iOrig != iDest)) { float k = (yDest - yOrig) / (xDest - xOrig); float n = yOrig - (xOrig - xOffset) * k; int i = iOrig - startIndex; while (iOrig < iDest) { ++i; if (iOrig >= startIndex && iOrig < iMax) { float y = (i * xStep) * k + n; setValue(iOrig, y); } ++iOrig; } while (iOrig > iDest) { if (iOrig >= startIndex && iOrig < iMax) { float y = (i * xStep) * k + n; setValue(iOrig, y); } --iOrig; --i; } } if (iDest >= startIndex && iDest < iMax) { if (editable) setValue(iDest, yDest); _currentIndex = iDest; _selectionSize = 1; } moveOrigin = pos; Q_EMIT(modified()); Q_EMIT(interacted()); } void QcMultiSlider::paintEvent(QPaintEvent* e) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; using QtCollider::Style::RoundRect; Q_UNUSED(e); QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); RoundRect frame(rect(), 2); drawSunken(&p, palette(), frame, background(), hasFocus() ? focusColor() : QColor()); if (!_values.count()) return; p.setRenderHint(QPainter::Antialiasing, false); bool horiz = ort == Qt::Horizontal; QRect bounds(contentsRect()); p.setClipRect(bounds); if (horiz) { p.translate(bounds.topLeft()); p.rotate(90); p.scale(1.0, -1.0); bounds.setSize(QSize(bounds.height(), bounds.width())); } else { p.translate(bounds.left(), bounds.top() + bounds.height()); p.scale(1.0, -1.0); } int count = _values.count() - startIndex; qreal spacing, width, yscale; spacing = elastic ? (qreal)bounds.width() / count : thumbSize.width() + gap; width = elastic ? qMin(spacing, (qreal)thumbSize.width()) : thumbSize.width(); yscale = bounds.height(); if (!isFilled) yscale -= thumbSize.height(); const QColor& fillClr = fillColor(); // selection if (highlight) { int i = _currentIndex - startIndex; int c = qMin(count - i, _selectionSize); if (c) { QRect r; r.setHeight(bounds.height()); r.setWidth(c * spacing); r.moveLeft(i * spacing); QColor hlColor = fillClr; hlColor.setAlpha(70); p.fillRect(r, hlColor); } } QPen pen; pen.setColor(strokeColor()); pen.setWidth(0); p.setPen(pen); // lines if (drawLines) { bool fill = isFilled & !drawRects; p.save(); p.setRenderHint(QPainter::Antialiasing, true); p.translate(spacing * 0.5, isFilled ? 0.0 : thumbSize.height() * 0.5); p.scale(1.0, (qreal)yscale); if (fill) p.setBrush(fillClr); QPainterPath path; // value line path.moveTo(0, _values[startIndex]); for (int i = 1; i < count; ++i) path.lineTo((qreal)i * spacing, _values[i + startIndex]); // reference line int refcount = _ref.count() - startIndex; if (refcount > 0 || fill) { qreal x, y; int i = count - 1; x = i * spacing; y = i < refcount ? _ref[i + startIndex] : 0.f; if (fill) path.lineTo(x, y); else path.moveTo(x, y); while (--i >= 0) { x = i * spacing; y = i < refcount ? _ref[i + startIndex] : 0.f; path.lineTo(x, y); } if (fill) path.closeSubpath(); } p.drawPath(path); p.restore(); } // rects if (drawRects) { p.setRenderHint(QPainter::Antialiasing, false); p.translate((spacing - width) * 0.5, 0); p.setBrush(fillClr); QRectF r; r.setWidth(width); if (isFilled) { int refcount = _ref.count() - startIndex; for (int i = 0; i < count; ++i) { int ref = (i < refcount ? _ref[i + startIndex] : 0.f) * yscale; int val = _values[i + startIndex] * yscale; r.moveLeft(i * spacing); r.moveTop(ref); r.setHeight(val - ref); if (horiz) p.drawRect(r.normalized().adjusted(0, 0, -1, -1)); else p.drawRect(r.normalized().adjusted(0, 1, -1, 0)); } } else { r.setHeight(thumbSize.height()); for (int i = 0; i < count; ++i) { r.moveLeft(i * spacing); r.moveTop(_values[i + startIndex] * yscale); if (horiz) p.drawRect(r.adjusted(0, 0, -1, -1)); else p.drawRect(r.adjusted(0, 1, -1, 0)); } } } } void QcMultiSlider::doAction() { Qt::KeyboardModifier ctrlMod = #ifdef Q_OS_MAC Qt::MetaModifier; #else Qt::ControlModifier; #endif if (QApplication::keyboardModifiers() & ctrlMod) Q_EMIT(metaAction()); else Q_EMIT(action()); }
11,699
C++
.cpp
356
25.424157
116
0.5592
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,820
QcCanvas.cpp
supercollider_supercollider/QtCollider/widgets/QcCanvas.cpp
/************************************************************************ * * Copyright 2010 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcCanvas.h" #include "../painting.h" #include "../Common.h" #include <QPainter> #include <QPaintEvent> #include <QBackingStore> QcCanvas::QcCanvas(QWidget* parent): QcCanvasBase(parent), _paint(false), _repaintNeeded(true), _clearOnRefresh(true), _clearOnce(false), _resize(false), _fps(60.f), _fpsActual(0.f), _timerId(0), _animating(false), _frameCount(0), _meterPeriod(1000), _meterFrames(0) {} float QcCanvas::frameRate() const { return _fpsActual; } void QcCanvas::setFrameRate(float rate) { if (rate != _fps) { _fps = rate; if (_animating && _fps > 0) { // restart animation timer with new frame rate killTimer(_timerId); _timerId = startTimer(1000.f / _fps); } } } void QcCanvas::setBackground(const QColor& c) { if (_bkg == c) return; _bkg = c; setAttribute(Qt::WA_OpaquePaintEvent, c.isValid() && c.alpha() == 255); setAttribute(Qt::WA_TranslucentBackground, c.isValid()); if (!testAttribute(Qt::WA_WState_InPaintEvent)) update(); } void QcCanvas::setBackgroundImage(const QtCollider::SharedImage& image, const QRectF& rect, int tileMode, double opacity) { _bkg_image.setImage(image, rect, tileMode, opacity); if (!testAttribute(Qt::WA_WState_InPaintEvent)) update(); } void QcCanvas::refresh() { _repaintNeeded = true; update(); } void QcCanvas::clear() { _clearOnce = true; } void QcCanvas::animate(bool on) { if (on) { if (!_animating && _fps > 0) { _frameCount = 0; _animating = true; _meterTime = QTime::currentTime(); _timerId = startTimer(1000.f / _fps); _fpsTimer.start(_meterPeriod, this); } } else if (_animating) { killTimer(_timerId); _fpsTimer.stop(); _animating = false; } } void QcCanvas::customEvent(QEvent* e) { if (e->type() == (QEvent::Type)QtCollider::Event_Refresh) { e->accept(); refresh(); } } void QcCanvas::changeEvent(QEvent* e) { if (e->type() == QEvent::PaletteChange) refresh(); } void QcCanvas::resizeEvent(QResizeEvent*) { _resize = true; refresh(); } void QcCanvas::paintEvent(QPaintEvent* e) { if (_paint && _repaintNeeded) { if (_resize) { qreal pixelRatio = backingStore()->window()->devicePixelRatio(); _pixmap = QPixmap(size() * pixelRatio); _pixmap.setDevicePixelRatio(pixelRatio); _resize = false; _clearOnce = true; } if (_clearOnRefresh || _clearOnce) { _pixmap.fill(QColor(0, 0, 0, 0)); _clearOnce = false; } bool opaque_before = testAttribute(Qt::WA_OpaquePaintEvent); QPainter pixPainter(&_pixmap); Q_EMIT(painting(&pixPainter)); _repaintNeeded = false; bool opaque_after = testAttribute(Qt::WA_OpaquePaintEvent); if (opaque_before && !opaque_after) { repaint(); return; } } QPainter painter(this); QPalette plt(palette()); if (_bkg.isValid()) painter.fillRect(e->rect(), _bkg); if (_bkg_image.isValid()) _bkg_image.paint(&painter, rect()); if (_paint) { qreal pixelRatio = backingStore()->window()->devicePixelRatio(); auto sourceRect = e->rect().intersected(QRect(0, 0, size().width(), size().height())); sourceRect = QRect(sourceRect.topLeft() * pixelRatio, sourceRect.size() * pixelRatio); painter.drawPixmap(e->rect(), _pixmap, sourceRect); } } void QcCanvas::timerEvent(QTimerEvent* e) { if (e->timerId() == _timerId) { ++_frameCount; ++_meterFrames; _repaintNeeded = true; repaint(); } else if (e->timerId() == _fpsTimer.timerId()) { // recalc actual fps float dTime = _meterTime.msecsTo(QTime::currentTime()); _fpsActual = (dTime > 0) ? (_meterFrames * 1000.f / dTime) : 0.f; // reset fps meter _meterTime = QTime::currentTime(); _meterFrames = 0; } }
5,095
C++
.cpp
151
27.549669
105
0.597722
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,821
QcSlider.cpp
supercollider_supercollider/QtCollider/widgets/QcSlider.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcSlider.h" #include "../QcWidgetFactory.h" #include <QMouseEvent> #include <QKeyEvent> #include <QWheelEvent> QC_DECLARE_QWIDGET_FACTORY(QcSlider); QcSlider::QcSlider(): QtCollider::Style::Client(this), _value(0.0), _step(0.0), _hndLen(20) { setFocusPolicy(Qt::StrongFocus); setOrientation(Qt::Vertical); setAttribute(Qt::WA_AcceptTouchEvents); } double QcSlider::pixelStep() { using namespace QtCollider::Style; QRect contRect(sunkenContentsRect(rect())); int range = (_ort == Qt::Horizontal) ? contRect.width() : contRect.height(); range -= _hndLen; if (range > 0) return 1.0 / range; else return 0.0; } void QcSlider::setValue(double val) { double step = _step; modifyStep(&step); if (step) val = qRound(val / step) * step; _value = qBound(0.0, val, 1.0); update(); } void QcSlider::increment(double factor) { double step = qMax(_step, pixelStep()); setValue(step * factor + _value); update(); } void QcSlider::decrement(double factor) { double step = qMax(_step, pixelStep()); setValue(-step * factor + _value); update(); } void QcSlider::setOrientation(int i) { _ort = (Qt::Orientation)i; if (_ort == Qt::Horizontal) setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); else setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); updateGeometry(); update(); } QSize QcSlider::sizeHint() const { if (orientation() == Qt::Horizontal) return QSize(qMax(_hndLen + 10, 150), 20); else return QSize(20, qMax(_hndLen + 10, 150)); } QSize QcSlider::minimumSizeHint() const { if (orientation() == Qt::Horizontal) return QSize(_hndLen + 10, 20); else return QSize(20, _hndLen + 10); } void QcSlider::mousePressEvent(QMouseEvent* e) { setValue(valueAt(e->pos())); update(); Q_EMIT(action()); } void QcSlider::mouseMoveEvent(QMouseEvent* e) { if (!e->buttons()) return; setValue(valueAt(e->pos())); update(); Q_EMIT(action()); } void QcSlider::wheelEvent(QWheelEvent* e) { double step = qMax(_step, pixelStep()); modifyStep(&step); const auto deltaX = e->pixelDelta().isNull() ? e->angleDelta().y() / 8.f : e->pixelDelta().y(); double dval = deltaX / 120.0 * step; setValue(_value + dval); Q_EMIT(action()); } void QcSlider::paintEvent(QPaintEvent* e) { using namespace QtCollider::Style; using QtCollider::Style::RoundRect; QPainter p(this); const QPalette& plt = palette(); p.save(); p.setRenderHint(QPainter::Antialiasing, true); QRect rGroove = rect(); // draw groove RoundRect shGroove(rGroove, 2); drawSunken(&p, plt, shGroove, grooveColor(), hasFocus() ? focusColor() : QColor()); // geometry QRect rHandle(thumbRect()); // draw handle RoundRect shHandle(rHandle, 2); drawRaised(&p, plt, shHandle, plt.color(QPalette::Button).lighter(105)); p.restore(); // draw marker QPen pen(knobColor()); pen.setWidth(2); p.setPen(pen); if (_ort == Qt::Horizontal) { qreal center = rHandle.center().x() + 1; QLine line(center, rHandle.top() + 3, center, rHandle.bottom() - 2); p.drawLine(line); pen.setColor(plt.color(QPalette::Light)); } else { qreal center = rHandle.center().y() + 1; QLine line(rHandle.left() + 3, center, rHandle.right() - 2, center); p.drawLine(line); pen.setColor(plt.color(QPalette::Light)); } } QRect QcSlider::thumbRect() { using namespace QtCollider::Style; QRect contRect(sunkenContentsRect(rect())); QRect r; if (_ort == Qt::Horizontal) { int pos = _value * (contRect.width() - _hndLen); r.setX(pos + contRect.left()); r.setY(contRect.top()); r.setSize(QSize(_hndLen, contRect.height())); } else { int pos = _value * (contRect.height() - _hndLen); r.setX(contRect.left()); r.setY(contRect.bottom() - pos - _hndLen + 1); r.setSize(QSize(contRect.width(), _hndLen)); } return r; } double QcSlider::valueAt(const QPoint& pos) { using namespace QtCollider::Style; QRect contRect(sunkenContentsRect(rect())); if (_ort == Qt::Horizontal) return xValue(pos.x(), contRect, QSize(_hndLen, 0)); else return yValue(pos.y(), contRect, QSize(0, _hndLen)); }
5,365
C++
.cpp
158
29.272152
99
0.635344
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,822
QcAbstractStepValue.cpp
supercollider_supercollider/QtCollider/widgets/QcAbstractStepValue.cpp
/************************************************************************ * * Copyright 2010 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include <QApplication> #include "QcAbstractStepValue.h" bool QcAbstractStepValue::modifyStep(double* pStep) { Qt::KeyboardModifiers mods = QApplication::keyboardModifiers(); if (!mods) return false; else if (mods & Qt::ShiftModifier) *pStep = *pStep * _shiftScale; else if (mods & Qt::ControlModifier) *pStep = *pStep * _ctrlScale; else if (mods & Qt::AltModifier) *pStep = *pStep * _altScale; else return false; return true; }
1,408
C++
.cpp
36
35.583333
74
0.641082
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,823
QcSlider2D.cpp
supercollider_supercollider/QtCollider/widgets/QcSlider2D.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcSlider2D.h" #include "../QcWidgetFactory.h" #include "../style/routines.hpp" #include <QKeyEvent> #include <QMouseEvent> #include <QApplication> #include <QPainter> QC_DECLARE_QWIDGET_FACTORY(QcSlider2D); QcSlider2D::QcSlider2D(): QtCollider::Style::Client(this), _x(0.0), _y(0.0), _thumbSize(QSize(20, 20)), _step(0.01) { setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAttribute(Qt::WA_AcceptTouchEvents); } void QcSlider2D::incrementX(double factor) { setValue(QPointF(_step * factor + _x, _y)); } void QcSlider2D::decrementX(double factor) { setValue(QPointF(-_step * factor + _x, _y)); } void QcSlider2D::incrementY(double factor) { setValue(QPointF(_x, _step * factor + _y)); } void QcSlider2D::decrementY(double factor) { setValue(QPointF(_x, -_step * factor + _y)); } QRect QcSlider2D::thumbRect() { using namespace QtCollider::Style; return QtCollider::Style::rect(QPointF(_x, _y), sunkenContentsRect(rect()), _thumbSize); } void QcSlider2D::setValue(const QPointF val, bool doAction) { double x = qMax(0.0, qMin(1.0, (double)val.x())); double y = qMax(0.0, qMin(1.0, (double)val.y())); if (x != _x || y != _y) { _x = x; _y = y; update(); if (doAction) Q_EMIT(action()); } } void QcSlider2D::mouseMoveEvent(QMouseEvent* ev) { using namespace QtCollider::Style; if (!ev->buttons()) return; QPointF val = QtCollider::Style::value(QPointF(ev->pos()), sunkenContentsRect(rect()), _thumbSize); setValue(val); } void QcSlider2D::mousePressEvent(QMouseEvent* ev) { using namespace QtCollider::Style; QPointF val = QtCollider::Style::value(QPointF(ev->pos()), sunkenContentsRect(rect()), _thumbSize); setValue(val); } void QcSlider2D::keyPressEvent(QKeyEvent* e) { double step = _step; switch (e->key()) { case Qt::Key_Up: modifyStep(&step); setValue(QPointF(_x, _y + step)); break; case Qt::Key_Down: modifyStep(&step); setValue(QPointF(_x, _y - step)); break; case Qt::Key_Right: modifyStep(&step); setValue(QPointF(_x + step, _y)); break; case Qt::Key_Left: modifyStep(&step); setValue(QPointF(_x - step, _y)); break; case Qt::Key_N: setValue(QPointF(0.0, 0.0)); break; case Qt::Key_X: setValue(QPointF(1.0, 1.0)); break; case Qt::Key_C: setValue(QPointF(0.5, 0.5)); break; case Qt::Key_R: Q_EMIT(randomize()); break; default: QWidget::keyPressEvent(e); } } void QcSlider2D::setBackgroundImage(const QtCollider::SharedImage& image, const QRectF& rect, int tileMode, double opacity) { _backgroundImage.setImage(image, rect, tileMode, opacity); } void QcSlider2D::paintEvent(QPaintEvent* e) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; using QtCollider::Style::RoundRect; Q_UNUSED(e); QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); QPalette plt = palette(); RoundRect frame(rect(), 2); drawSunken(&p, plt, frame, grooveColor(), hasFocus() ? focusColor() : QColor()); if (_backgroundImage.isValid()) _backgroundImage.paint(&p, rect()); Ellipse thumb(thumbRect()); drawRaised(&p, plt, thumb, plt.color(QPalette::Button).lighter(105)); QRectF r(thumb._rect); qreal wdif = r.width() * 0.3; qreal hdif = r.height() * 0.3; p.setPen(Qt::NoPen); p.setBrush(knobColor()); p.drawEllipse(r.adjusted(wdif, hdif, -wdif, -hdif)); }
4,615
C++
.cpp
124
32.225806
117
0.638236
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,824
QcListWidget.cpp
supercollider_supercollider/QtCollider/widgets/QcListWidget.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcListWidget.h" #include "../QcWidgetFactory.h" #include <QKeyEvent> #include <QModelIndex> class QcListWidgetFactory : public QcWidgetFactory<QcListWidget> { void initialize(QWidgetProxy* p, QcListWidget* l) { p->setMouseEventWidget(l->viewport()); } }; QC_DECLARE_FACTORY(QcListWidget, QcListWidgetFactory); QcListWidget::QcListWidget(): _emitAction(true) { connect(this, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onCurrentItemChanged())); } void QcListWidget::setItems(const QVariantList& items) { _emitAction = false; clear(); Q_FOREACH (const QVariant& item, items) addItem(item.toString()); setCurrentRow(0); _emitAction = true; } void QcListWidget::setColors(const QVariantList& colors) const { int cc = colors.count(); int ic = count(); for (int i = 0; i < cc && i < ic; ++i) { QListWidgetItem* it = item(i); QColor color(colors[i].value<QColor>()); if (color.isValid()) it->setBackground(color); } } void QcListWidget::setCurrentRowWithoutAction(int row) { bool b = _emitAction; _emitAction = false; setCurrentRow(row); _emitAction = b; } QVariantList QcListWidget::selection() const { QModelIndexList modelIndexes = QListView::selectedIndexes(); QVariantList indexes; Q_FOREACH (const QModelIndex& index, modelIndexes) indexes << index.row(); return indexes; } void QcListWidget::setSelection(const QVariantList& list) { clearSelection(); Q_FOREACH (const QVariant& var, list) { int row = var.toInt(); QListWidgetItem* item = QListWidget::item(row); if (item) item->setSelected(true); } } void QcListWidget::onCurrentItemChanged() { if (_emitAction) Q_EMIT(action()); } void QcListWidget::keyPressEvent(QKeyEvent* e) { QListWidget::keyPressEvent(e); switch (e->key()) { case Qt::Key_Return: case Qt::Key_Enter: Q_EMIT(returnPressed()); e->accept(); break; case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_PageUp: case Qt::Key_PageDown: case Qt::Key_Home: case Qt::Key_End: // Prevent propagating to parent when scroller reaches minimum or maximum: e->accept(); default: break; } }
3,290
C++
.cpp
97
29.57732
118
0.659434
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,825
QcNumberBox.cpp
supercollider_supercollider/QtCollider/widgets/QcNumberBox.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcNumberBox.h" #include "../Common.h" #include "../QcWidgetFactory.h" #include <QKeyEvent> #include <QMouseEvent> #include <QApplication> #include <math.h> #include <qmath.h> QC_DECLARE_QWIDGET_FACTORY(QcNumberBox); QcNumberBox::QcNumberBox(): scroll(true), lastPos(0), editedTextColor(QColor("red")), normalTextColor(palette().color(QPalette::Text)), _validator(new QDoubleValidator(this)), step(0.1f), scrollStep(1.0f), dragDist(10.f), _value(0.), _valueType(Number), _minDec(0), _maxDec(2) { _validator->setDecimals(_maxDec); setValidator(_validator); // Do not display thousands separator. It only eats up precious space. QLocale loc(locale()); loc.setNumberOptions(QLocale::OmitGroupSeparator); setLocale(loc); setLocked(true); setAttribute(Qt::WA_AcceptTouchEvents); connect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); connect(this, SIGNAL(valueChanged()), this, SLOT(updateText()), Qt::QueuedConnection); setValue(0); } void QcNumberBox::setLocked(bool locked) { if (locked) { setReadOnly(true); setSelection(0, 0); } else { setReadOnly(false); } updateTextColor(); } void QcNumberBox::setTextColor(const QColor& c) { if (c.isValid()) { normalTextColor = c; updateTextColor(); } } void QcNumberBox::setEditedTextColor(const QColor& c) { if (c.isValid()) { editedTextColor = c; updateTextColor(); } } void QcNumberBox::setValue(double val) { if (val > _validator->top()) val = _validator->top(); if (val < _validator->bottom()) val = _validator->bottom(); val = roundedVal(val); _value = val; _valueType = Number; Q_EMIT(valueChanged()); } void QcNumberBox::setInfinite(bool positive) { _valueType = positive ? Infinite : InfiniteNegative; Q_EMIT(valueChanged()); } void QcNumberBox::setNaN() { _valueType = NaN; Q_EMIT(valueChanged()); } void QcNumberBox::setTextValue(const QString& str) { _valueType = Text; setText(str); } double QcNumberBox::value() const { return _value; } void QcNumberBox::setMinimum(double min) { _validator->setBottom(min); if (_valueType == Number) setValue(_value); // clip current value } void QcNumberBox::setMaximum(double max) { _validator->setTop(max); if (_valueType == Number) setValue(_value); // clip current value } void QcNumberBox::setDecimals(int d) { if (d < 0) return; _minDec = _maxDec = d; _validator->setDecimals(d); if (_valueType == Number) setValue(_value); // round current value } void QcNumberBox::setMinDecimals(int d) { if (d < 0) return; _minDec = d; if (_minDec > _maxDec) { _maxDec = d; _validator->setDecimals(d); } if (_valueType == Number) setValue(_value); // round current value } void QcNumberBox::setMaxDecimals(int d) { if (d < 0) return; _maxDec = d; if (_maxDec < _minDec) _minDec = d; _validator->setDecimals(d); if (_valueType == Number) setValue(_value); // round current value } void QcNumberBox::increment(double factor) { if (!isReadOnly() || _valueType != Number) return; setValue(value() + (step * factor)); Q_EMIT(action()); } void QcNumberBox::decrement(double factor) { if (!isReadOnly() || _valueType != Number) return; setValue(value() - (step * factor)); Q_EMIT(action()); } void QcNumberBox::onEditingFinished() { if (isReadOnly()) return; setValue(locale().toDouble(text())); Q_EMIT(action()); } void QcNumberBox::updateText() { QString str; switch (_valueType) { case Number: str = stringForVal(_value); break; case Text: return; // text was already set case Infinite: str = "+inf"; break; case InfiniteNegative: str = "-inf"; break; case NaN: str = "NaN"; break; } blockSignals(true); setText(str); // Set cursor to beginning so most significant digits are shown // if widget size too small. setCursorPosition(0); setLocked(true); blockSignals(false); } void QcNumberBox::stepBy(int steps, double stepSize) { if (_valueType != Number) return; modifyStep(&stepSize); setValue(value() + (steps * stepSize)); } double QcNumberBox::roundedVal(double val) { double k = pow(10, _maxDec); return qRound(val * k) / k; } QString QcNumberBox::stringForVal(double val) { QLocale loc = locale(); QString str = loc.toString(val, 'f', _maxDec); int i = str.indexOf(loc.decimalPoint()); if (i > -1) { QString dec = str.mid(i + 1); while (dec.size() > _minDec && dec.endsWith('0')) dec.chop(1); if (dec.isEmpty()) str = str.left(i); else str = str.left(i + 1) + dec; } return str; } void QcNumberBox::updateTextColor() { QPalette p(palette()); p.setColor(QPalette::Text, isReadOnly() ? normalTextColor : editedTextColor); setPalette(p); } void QcNumberBox::keyPressEvent(QKeyEvent* event) { if (!isReadOnly()) return QLineEdit::keyPressEvent(event); int key = event->key(); if (key == Qt::Key_Up) { stepBy(1, step); Q_EMIT(action()); return; } else if (key == Qt::Key_Down) { stepBy(-1, step); Q_EMIT(action()); return; } else { // unlock typing if valid char is entered QString t = event->text(); int i = 0; if (!t.isEmpty() && (_validator->validate(t, i) != QValidator::Invalid)) { blockSignals(true); clear(); blockSignals(false); setLocked(false); } } QLineEdit::keyPressEvent(event); } void QcNumberBox::mouseDoubleClickEvent(QMouseEvent* event) { Q_UNUSED(event); setCursorPosition(cursorPositionAt(event->pos())); setLocked(false); } void QcNumberBox::mousePressEvent(QMouseEvent* event) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) lastPos = event->globalY(); #else lastPos = event->globalPosition().y(); #endif // If locked, prevent cursor position change. Cursor has to stay at 0 // so most significant digits are shown if widget size too small. if (isReadOnly()) return; QLineEdit::mousePressEvent(event); } void QcNumberBox::mouseMoveEvent(QMouseEvent* event) { if (scroll && isReadOnly() && _valueType == Number && (event->buttons() & Qt::LeftButton)) { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) int steps = (event->globalY() - lastPos) / dragDist; #else int steps = (event->globalPosition().y() - lastPos) / dragDist; #endif if (steps != 0) { lastPos = lastPos + (steps * dragDist); stepBy(-steps, scrollStep); Q_EMIT(action()); } } else QLineEdit::mouseMoveEvent(event); } void QcNumberBox::wheelEvent(QWheelEvent* event) { if (scroll && isReadOnly() && _valueType == Number && event->angleDelta().x()) { const QPointF delta = event->pixelDelta().isNull() ? event->angleDelta() / 8.f // scaled to return steps of 15 : event->pixelDelta() * 0.25f; // this matches old scaling of delta stepBy(delta.x() > 0 ? 1 : -1, scrollStep); Q_EMIT(action()); } } #if 0 NumberBoxWidget::NumberBoxWidget() : modifier( 0 ), scrollStep( 1 ) { ScrollLineEdit *scrollLineEdit = new ScrollLineEdit(); scrollLineEdit->setScroll( true ); setLineEdit( scrollLineEdit ); connect( scrollLineEdit, SIGNAL( scrolled(int) ), this, SLOT( scrollBy(int) ) ); connect( this, SIGNAL( editingFinished() ), this, SLOT( onEditingFinished() ) ); } void NumberBoxWidget::setScroll( bool b ) { ScrollLineEdit *edit = qobject_cast<ScrollLineEdit*>( lineEdit() ); edit->setScroll( b ); } void NumberBoxWidget::stepBy( int steps ) { stepBy( steps, singleStep() ); } void NumberBoxWidget::scrollBy( int steps ) { stepBy( steps, scrollStep ); } void NumberBoxWidget::onEditingFinished() { ScrollLineEdit *edit = qobject_cast<ScrollLineEdit*>( lineEdit() ); edit->setLocked( true ); } void NumberBoxWidget::stepBy( int steps, float stepSize ) { modifier->modifyStep( &stepSize ); double val = qMin( maximum(), value() + (steps * stepSize) ); val = qMax( minimum(), val ); setValue( val ); } void NumberBoxWidget::keyPressEvent ( QKeyEvent * event ) { if( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return ) { interpretText(); Q_EMIT( editingFinished() ); } else QDoubleSpinBox::keyPressEvent( event ); } #endif
9,729
C++
.cpp
325
25.16
96
0.633234
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,826
QcWindow.cpp
supercollider_supercollider/QtCollider/widgets/QcWindow.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcWindow.h" #include "../QcWidgetFactory.h" #include "../QWidgetProxy.h" #include <QShortcut> #include <QApplication> #include <QScreen> class QcWindowFactory : public QcObjectFactory<QcWindow> { // NOTE: use basic object contruction, but return widget proxy public: virtual QObjectProxy* proxy(QcWindow* obj, PyrObject* sc_obj) { QObjectProxy* proxy = new QWidgetProxy(obj, sc_obj); QObject::connect(obj, SIGNAL(painting(QPainter*)), proxy, SLOT(customPaint(QPainter*))); return proxy; } }; class QcScrollWindowFactory : public QcObjectFactory<QcScrollWindow> { // NOTE: use basic object contruction, but return widget proxy // NOTE: painting will be performed by QcScrollWidget and its factory public: virtual QObjectProxy* proxy(QcScrollWindow* obj, PyrObject* sc_obj) { return new QWidgetProxy(obj, sc_obj); } }; QC_DECLARE_FACTORY(QcWindow, QcWindowFactory); QC_DECLARE_FACTORY(QcScrollWindow, QcScrollWindowFactory); static void qcInitWindow(QWidget* window, const QString& title, const QRectF& geom_, bool resizable, bool frame) { // window title window->setWindowTitle(title); // size, resizability QRect geom(geom_.toRect()); if (geom.isEmpty()) { geom = QApplication::primaryScreen()->availableGeometry(); geom.setSize(window->sizeHint()); } if (resizable) { window->setGeometry(geom); } else { window->move(geom.topLeft()); window->setFixedSize(geom.size()); } // frameless? if (!frame) window->setWindowFlags(window->windowFlags() | Qt::FramelessWindowHint); // Ctrl+W shortcut: close the window QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_W), window); QObject::connect(closeShortcut, SIGNAL(activated()), window, SLOT(close())); } QcWindow::QcWindow(const QString& title, const QRectF& geom, bool resizable, bool frame) { qcInitWindow(this, title, geom, resizable, frame); } QcScrollWindow::QcScrollWindow(const QString& title, const QRectF& geom, bool resizable, bool frame) { qcInitWindow(this, title, geom, resizable, frame); }
3,072
C++
.cpp
71
39.507042
114
0.693365
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,827
QcRangeSlider.cpp
supercollider_supercollider/QtCollider/widgets/QcRangeSlider.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcRangeSlider.h" #include "../QcWidgetFactory.h" #include "../style/routines.hpp" #include <QKeyEvent> #include <QMouseEvent> #include <QApplication> #include <QPainter> #define HND 10 QC_DECLARE_QWIDGET_FACTORY(QcRangeSlider); QcRangeSlider::QcRangeSlider(): QtCollider::Style::Client(this), _lo(0.0), _hi(1.0), _step(0.01f), mouseMode(None) { setFocusPolicy(Qt::StrongFocus); setOrientation(Qt::Vertical); setAttribute(Qt::WA_AcceptTouchEvents); } void QcRangeSlider::setOrientation(int orientation) { _ort = asOrientationWithDefault(orientation, Qt::Vertical); if (_ort == Qt::Horizontal) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); } else { setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); } updateGeometry(); update(); } void QcRangeSlider::setLoValue(double val) { val = qMax(0.0, qMin(1.0, val)); if (val <= _hi) { _lo = val; } else { _lo = _hi; _hi = val; } update(); } void QcRangeSlider::setHiValue(double val) { val = qMax(0.0, qMin(1.0, val)); if (val >= _lo) { _hi = val; } else { _hi = _lo; _lo = val; } update(); } void QcRangeSlider::setRange(double val, double range) { range = qBound(0.0, range, 1.0); _lo = qBound(0.0, val, 1.0 - range); _hi = _lo + range; update(); } QSize QcRangeSlider::sizeHint() const { return (_ort == Qt::Horizontal ? QSize(150, 20) : QSize(20, 150)); } QSize QcRangeSlider::minimumSizeHint() const { return (_ort == Qt::Horizontal ? QSize(30, 20) : QSize(20, 30)); } void QcRangeSlider::increment(double factor) { moveBy(factor * _step); } void QcRangeSlider::decrement(double factor) { moveBy(-factor * _step); } void QcRangeSlider::increment() { double step = _step; modifyStep(&step); moveBy(step); } void QcRangeSlider::decrement() { double step = _step; modifyStep(&step); moveBy(-step); } QRect QcRangeSlider::thumbRect() { using namespace QtCollider::Style; QRect contRect(sunkenContentsRect(rect())); int hnd2 = HND * 2; if (_ort == Qt::Horizontal) { double valRange = contRect.width() - hnd2; double left = _lo * valRange; double right = _hi * valRange; right += hnd2; return QRect(left + contRect.x(), contRect.y(), right - left, contRect.height()); } else { double valRange = contRect.height() - hnd2; int up = (1.0 - _hi) * valRange; int down = (1.0 - _lo) * valRange; down += hnd2; return QRect(contRect.x(), contRect.y() + up, contRect.width(), down - up); } } double QcRangeSlider::valueFromPos(const QPoint& pos) { using namespace QtCollider::Style; bool horiz = _ort == Qt::Horizontal; QSize margins = horiz ? QSize(HND * 2, 0) : QSize(0, HND * 2); QRect valBounds = marginsRect(sunkenContentsRect(rect()), margins); return horiz ? xValue(pos.x(), valBounds) : yValue(pos.y(), valBounds); } void QcRangeSlider::moveBy(double dif) { if (_lo + dif < 0.0) { _hi += 0.0 - _lo; _lo = 0.0; } else if (_hi + dif > 1.0) { _lo += 1.0 - _hi; _hi = 1.0; } else { _lo += dif; _hi += dif; } update(); } void QcRangeSlider::mouseMoveEvent(QMouseEvent* e) { using namespace QtCollider::Style; if (!e->buttons()) return; if (mouseMode == SetHi || mouseMode == SetLo) { double val = valueFromPos(e->pos()); if (mouseMode == SetLo) { if (val > _hi) mouseMode = SetHi; setLoValue(val); } else if (mouseMode == SetHi) { if (val < _lo) mouseMode = SetLo; setHiValue(val); } } else if (mouseMode != None) { QPoint pt = e->pos() - dragOrigin; QRect contRect(sunkenContentsRect(rect())); double dif; if (_ort == Qt::Horizontal) { double range = contRect.width() - HND * 2; dif = range > 0 ? pt.x() / range : 0.0; } else { double range = contRect.height() - HND * 2; dif = range > 0 ? -pt.y() / range : 0.0; } if (dif != 0.0) { switch (mouseMode) { case Move: setRange(dragVal + dif, dragRange); break; case MoveHi: setHiValue(qMax(dragVal + dif, (double)_lo)); break; case MoveLo: setLoValue(qMin(dragVal + dif, (double)_hi)); break; default:; } } } Q_EMIT(action()); } void QcRangeSlider::mousePressEvent(QMouseEvent* e) { using namespace QtCollider::Style; if (e->modifiers() & Qt::ShiftModifier) { double center = (_hi + _lo) * 0.5; double val = valueFromPos(e->pos()); if (val < center) { mouseMode = SetLo; setLoValue(val); } else { mouseMode = SetHi; setHiValue(val); } Q_EMIT(action()); } else { QRect thumb(thumbRect()); int len, pos; if (_ort == Qt::Horizontal) { len = thumb.width(); pos = e->pos().x() - thumb.left(); } else { len = thumb.height(); pos = thumb.top() + len - e->pos().y(); } if (pos < 0 || pos > len) return; dragOrigin = e->pos(); if (pos < HND) { mouseMode = MoveLo; dragVal = _lo; } else if (pos >= len - HND) { mouseMode = MoveHi; dragVal = _hi; } else { mouseMode = Move; dragVal = _lo; dragRange = _hi - _lo; } } update(); } void QcRangeSlider::mouseReleaseEvent(QMouseEvent* e) { Q_UNUSED(e); mouseMode = None; } void QcRangeSlider::keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Qt::Key_Up: case Qt::Key_Right: increment(); break; case Qt::Key_Down: case Qt::Key_Left: decrement(); break; case Qt::Key_A: _lo = 0.0; _hi = 1.0; update(); break; case Qt::Key_N: _lo = 0.0; _hi = 0.0; update(); break; case Qt::Key_X: _lo = 1.0; _hi = 1.0; update(); break; case Qt::Key_C: _lo = 0.5; _hi = 0.5; update(); break; default: return QWidget::keyPressEvent(e); } Q_EMIT(action()); } inline void drawMarker(QPainter* p, const QColor& color, Qt::Orientation ort, bool first, const QPoint& pt, int len) { p->save(); p->setRenderHint(QPainter::Antialiasing, false); QPen pen(color); bool vert = ort == Qt::Vertical; if (vert) { pen.setWidth(1); p->setPen(pen); p->drawPoint(QPoint(pt.x() + len * 0.5, first ? pt.y() - 5 : pt.y() + 5)); pen.setWidth(2); p->setPen(pen); QLine line(pt.x() + 1, pt.y(), pt.x() + len - 1, pt.y()); p->drawLine(line); } else { pen.setWidth(1); p->setPen(pen); p->drawPoint(QPoint(first ? pt.x() - 5 : pt.x() + 5, pt.y() + len * 0.5)); pen.setWidth(2); p->setPen(pen); QLine line(pt.x(), pt.y() + 1, pt.x(), pt.y() + len - 1); p->drawLine(line); } p->restore(); } void QcRangeSlider::paintEvent(QPaintEvent* e) { using namespace QtCollider::Style; using QtCollider::Style::RoundRect; Q_UNUSED(e); QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); const QPalette& plt = palette(); const QColor& knobClr = knobColor(); RoundRect frame(rect(), 2); drawSunken(&p, plt, frame, grooveColor(), hasFocus() ? focusColor() : QColor()); QRect contRect(sunkenContentsRect(rect())); QRect hndRect; QRect valRect; int HND2 = HND * 2; bool horiz = _ort == Qt::Horizontal; if (horiz) { double valRange = contRect.width() - HND2; int lo = _lo * valRange; int hi = _hi * valRange; valRect = QRect(lo + HND + contRect.x(), contRect.y(), hi - lo, contRect.height()); hndRect = valRect.adjusted(-HND, 0, HND, 0); } else { double valRange = contRect.height() - HND2; int hi = _hi * valRange; int lo = _lo * valRange; valRect = QRect(contRect.x(), contRect.y() + contRect.height() - hi - HND, contRect.width(), hi - lo); hndRect = valRect.adjusted(0, -HND, 0, HND); } // handle RoundRect handle(hndRect, 2); drawRaised(&p, plt, handle, plt.color(QPalette::Button).lighter(105)); // markers if (horiz) { int mark_len = hndRect.height() - 4; QPoint pt(hndRect.left() + HND, hndRect.top() + 2); drawMarker(&p, knobClr, _ort, true, pt, mark_len); pt.setX(hndRect.right() - HND + 1); drawMarker(&p, knobClr, _ort, false, pt, mark_len); } else { int mark_len = hndRect.width() - 4; QPoint pt(hndRect.left() + 2, hndRect.top() + HND); drawMarker(&p, knobClr, _ort, true, pt, mark_len); pt.setY(hndRect.bottom() - HND + 1); drawMarker(&p, knobClr, _ort, false, pt, mark_len); } // value region if (horiz ? valRect.width() > 2 : valRect.height() > 2) { p.setRenderHint(QPainter::Antialiasing, false); QColor c(knobClr); c.setAlpha(50); p.setPen(Qt::NoPen); p.setBrush(c); if (horiz) p.drawRect(valRect.adjusted(1, 2, -1, -2)); else p.drawRect(valRect.adjusted(2, 1, -2, -1)); } } Qt::Orientation QcRangeSlider::asOrientationWithDefault(int orientationValue, Qt::Orientation defaultOrientation) { if (orientationValue == Qt::Horizontal || orientationValue == Qt::Vertical) return static_cast<Qt::Orientation>(orientationValue); return defaultOrientation; }
10,933
C++
.cpp
331
26.102719
118
0.561936
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,828
QcLevelIndicator.cpp
supercollider_supercollider/QtCollider/widgets/QcLevelIndicator.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcLevelIndicator.h" #include "../QcWidgetFactory.h" #include <QPainter> #include <QPainterPath> QC_DECLARE_QWIDGET_FACTORY(QcLevelIndicator); QcLevelIndicator::QcLevelIndicator(): QtCollider::Style::Client(this), _value(0.f), _warning(0.6), _critical(0.8), _peak(0.f), _drawPeak(false), _ticks(0), _majorTicks(0), _stepWidth(10), _style(LevelIndicatorStyle::Continuous), _clipped(false), _meterColor(0, 255, 0), _warningColor(255, 255, 0), _criticalColor(255, 100, 0) { _clipTimer = new QTimer(this); _clipTimer->setSingleShot(true); _clipTimer->setInterval(1000); connect(_clipTimer, SIGNAL(timeout()), this, SLOT(clipTimeout())); } const QColor QcLevelIndicator::valueColor(float value) { if (value > _critical) return _criticalColor; else if (value > _warning) return _warningColor; else return _meterColor; } void QcLevelIndicator::clipTimeout() { _clipped = false; update(); } void QcLevelIndicator::paintEvent(QPaintEvent* e) { QPainter p(this); bool vertical = height() >= width(); float groove = vertical ? width() : height(); float length = vertical ? height() : width(); if (!vertical) { p.scale(-1, 1); p.translate(0, 0); p.rotate(90); } else { p.scale(1, -1); p.translate(0, -height()); } QPalette plt = palette(); if (_ticks || _majorTicks) groove -= 6; float colorValue = _drawPeak ? _peak : _value; if (colorValue > _critical) { _clipTimer->stop(); _clipped = true; } else if (_clipped && !_clipTimer->isActive()) { _clipTimer->start(); } p.fillRect(QRectF(0, 0, groove, length), grooveColor()); QRectF r; r.setWidth(groove); r.setY(0); p.setRenderHint(QPainter::Antialiasing, true); switch (_style) { case Continuous: { r.setHeight(_value * length); p.fillRect(r, valueColor(colorValue)); if (_drawPeak && _peak > 0.f) { // compensate for border and peak line width float val = _peak * (length - 4) + 2; QPen pen(valueColor(_peak)); pen.setWidth(2); pen.setCapStyle(Qt::FlatCap); p.setPen(pen); p.drawLine(0.f, val, groove, val); } break; } case LED: { float ledBaseline = 0; float spaceWidth = _stepWidth <= 3 ? 1 : 2; float cornerWidth = _stepWidth <= 3 ? 0 : 1.2; float stepSpacing = _stepWidth + spaceWidth; float adjustedLength = std::floor(length / stepSpacing) * stepSpacing; r.setHeight(_stepWidth); QPainterPath path; path.addRoundedRect(r, cornerWidth, cornerWidth); while (ledBaseline < adjustedLength * _value) { float normValue = (ledBaseline / adjustedLength); // 0..1 scaled value of the BOTTOM of the rect float nextValue = ((ledBaseline + _stepWidth + spaceWidth) / adjustedLength); QColor c = valueColor(normValue); if (nextValue > _value) { // last cell c = valueColor(_value); c.setAlphaF(c.alphaF() * (0.5 + 0.5 * ((_value - normValue) / (nextValue - normValue)))); } p.fillPath(path, QBrush(c)); ledBaseline += stepSpacing; path.translate(0, stepSpacing); } if (_drawPeak && _peak > 0.f) { float peak = std::floor(_peak * adjustedLength / stepSpacing) * stepSpacing; peak = std::min(peak, adjustedLength - stepSpacing); // For _peak == 1, don't run off edge of widget QPainterPath peakPath; peakPath.addRoundedRect(r, cornerWidth, cornerWidth); peakPath.translate(0, peak); p.fillPath(peakPath, QBrush(valueColor(_peak))); } break; } default: break; } p.setRenderHint(QPainter::Antialiasing, false); if (_ticks) { QPen pen(plt.color(QPalette::WindowText)); pen.setCapStyle(Qt::FlatCap); p.setPen(pen); float dVal = (_ticks > 1) ? (length - 1) / (float)(_ticks - 1) : 0.f; float t = 0; while (t < _ticks) { float v = t * dVal; p.drawLine(groove, v, width(), v); t++; } } if (_majorTicks) { QPen pen(plt.color(QPalette::WindowText)); pen.setCapStyle(Qt::FlatCap); pen.setWidth(3); p.setPen(pen); float dVal = (_majorTicks > 1) ? (length - 3) / (float)(_majorTicks - 1) : 0.f; float t = 0; while (t < _majorTicks) { float v = (int)(t * dVal) + 1; if (vertical) p.drawLine(groove, v, width(), v); else p.drawLine(v, groove, v, height()); t++; } } }
5,816
C++
.cpp
164
28.182927
112
0.577833
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,829
QcScopeShm.cpp
supercollider_supercollider/QtCollider/widgets/QcScopeShm.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of Qt GUI for SuperCollider. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcScopeShm.h" #include "scope_shm_interface.hpp" #include "../QcWidgetFactory.h" #include "../debug.h" #include <QPainter> #include <QPainterPath> #include <QTimer> #include <QResizeEvent> #include <QWindow> #include <QBackingStore> QC_DECLARE_QWIDGET_FACTORY(QcScopeShm); QcScopeShm::QcScopeShm(): _srvPort(-1), _scopeIndex(-1), _shm(new ScopeShm(this)), _running(false), _data(0), _availableFrames(0), xOffset(0.f), yOffset(0.f), xZoom(1.f), yZoom(1.f), _style(0), _bkg(QColor(0, 0, 0)), _fill(true) { setAttribute(Qt::WA_OpaquePaintEvent, true); setAutoFillBackground(false); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); timer = new QTimer(this); timer->setInterval(50); connect(timer, SIGNAL(timeout()), this, SLOT(updateScope())); } QcScopeShm::~QcScopeShm() { stop(); } void QcScopeShm::setServerPort(int port) { if (_running) { qcWarningMsg("QScope: Can not change server port while running!"); return; } _srvPort = port; } void QcScopeShm::setBufferNumber(int n) { if (_running) { // TODO: release used reader? initScopeReader(_shm, n); } _scopeIndex = n; } void QcScopeShm::setWaveColors(const QVariantList& newColors) { colors.clear(); Q_FOREACH (const QVariant& var, newColors) { QColor color = var.value<QColor>(); if (!color.isValid()) colors.append(QColor(0, 0, 0)); else colors.append(color); } } int QcScopeShm::updateInterval() const { return timer->interval(); } void QcScopeShm::setUpdateInterval(int interval) { timer->setInterval(qMax(0, interval)); } void QcScopeShm::start() { if (_running) return; if (_srvPort < 0 || _scopeIndex < 0) return; connectSharedMemory(_srvPort); if (!_shm->client) { stop(); return; } initScopeReader(_shm, _scopeIndex); timer->start(); _running = true; } void QcScopeShm::stop() { // TODO: release used reader? delete _shm->client; _shm->client = 0; timer->stop(); _running = false; } void QcScopeShm::updateScope() { bool valid = _shm->reader.valid(); // qcDebugMsg(1, tr("valid = %1").arg(valid)); if (!valid) return; bool ok = _shm->reader.pull(_availableFrames); // qcDebugMsg(1, tr("Got %1 frames").arg(_availableFrames) ); if (ok) { _data = _shm->reader.data(); update(); } } void QcScopeShm::resizeEvent(QResizeEvent* ev) { qreal ratio = backingStore()->window()->devicePixelRatio(); _pixmap = QPixmap(ev->size() * ratio); _pixmap.setDevicePixelRatio(ratio); } void QcScopeShm::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QPainter p; _pixmap.fill(_bkg); if (_running && _availableFrames) { int chanCount = _shm->reader.channels(); int maxFrames = _shm->reader.max_frames(); QRect area(_pixmap.rect()); area.setSize(area.size() / _pixmap.devicePixelRatio()); p.begin(&_pixmap); switch (_style) { case 0: paint1D(false, chanCount, maxFrames, _availableFrames, area, p); break; case 1: paint1D(true, chanCount, maxFrames, _availableFrames, area, p); break; case 2: paint2D(chanCount, maxFrames, _availableFrames, area, p); break; } p.end(); } p.begin(this); p.drawPixmap(0, 0, _pixmap); } void QcScopeShm::paint1D(bool overlapped, int chanCount, int maxFrames, int frameCount, const QRect& area, QPainter& painter) { // qcDebugMsg( 0, tr("Drawing: data %1 / channels %2 / max-size %3").arg(_data!=0).arg(chanCount).arg(maxFrames) ); if (frameCount < 2 || area.width() < 1 || area.height() < 1) return; float yRatio = -yZoom * area.height() * 0.5; if (!overlapped) yRatio /= chanCount; float yHeight = area.height(); if (!overlapped) yHeight /= chanCount; QPen pen; pen.setWidth(0); // width==0 means width 1 regardless of transformations pen.setCapStyle(Qt::FlatCap); if (frameCount < area.width()) { float xRatio = xZoom * area.width() / (frameCount - 1); for (int ch = 0; ch < chanCount; ch++) { float* frameData = _data + (ch * maxFrames); // frame vector float yOrigin = yHeight * (overlapped ? 0.5 : ch + 0.5); QColor strokeColor = ch < colors.count() ? colors[ch] : QColor(255, 255, 255); QColor fillColor(strokeColor); fillColor.setAlpha(0.65 * 255); pen.setColor(strokeColor); painter.save(); painter.translate(area.x(), area.y() + yOrigin); painter.scale(xRatio, yRatio); painter.setPen(pen); QPainterPath path; path.moveTo(xOffset, frameData[0]); for (int f = 1; f < frameCount; ++f) path.lineTo(xOffset + f, frameData[f]); if (_fill) { path.lineTo(xOffset + frameCount, 0); path.lineTo(0, 0); path.lineTo(xOffset, frameData[0]); painter.fillPath(path, QBrush(fillColor)); } painter.drawPath(path); painter.restore(); } } else { int w = area.width(); float fpp = frameCount / (float)w; // frames per x pixel for (int ch = 0; ch < chanCount; ch++) { float* frameData = _data + (ch * maxFrames); // frame vector float yOrigin = yHeight * (overlapped ? 0.5 : ch + 0.5); QColor strokeColor = ch < colors.count() ? colors[ch] : QColor(255, 255, 255); QColor fillColor(strokeColor); fillColor.setAlpha(0.65 * 255); painter.save(); painter.translate(area.x(), area.y() + yOrigin); painter.setPen(pen); qreal ratio = 1.0 / _pixmap.devicePixelRatio(); QPainterPath pathLine; QPainterPath pathFill; int frame = 1; float min, max; min = max = frameData[0]; for (qreal pixel = 0; pixel < w; pixel += ratio) { for (; frame < fpp * pixel; ++frame) { float const d = frameData[frame]; if (d < min) min = d; if (d > max) max = d; } // Make sure min is always lesser; otherwise if no frames are read // this produces odd-looking artifacts as min and max are accidentally // swapped twice and a line-pixel-line sequence is drawn. // TODO: interpolate in this case somehow? if (min > max) std::swap(min, max); float y = max * yRatio; pathLine.moveTo(pixel, y); y = qMax(min * yRatio, y + 1); pathLine.lineTo(pixel, y); if (_fill) { pathFill.moveTo(pixel, y); pathFill.lineTo(pixel, 0); } // flip min/max to ensure continuity std::swap(min, max); } pen.setColor(strokeColor); painter.strokePath(pathLine, pen); if (_fill) { pen.setColor(fillColor); painter.strokePath(pathFill, pen); } painter.restore(); } } } void QcScopeShm::paint2D(int chanCount, int maxFrames, int frameCount, const QRect& area, QPainter& painter) { int minSize = qMin(area.width(), area.height()); // NOTE: use yZoom for both axis, since both represent value, as opposed to index float xRatio = yZoom * minSize * 0.5; float yRatio = -yZoom * minSize * 0.5; QPoint center = area.center(); QPen pen; pen.setWidth(0); // width==0 means width 1 regardless of transformations pen.setCapStyle(Qt::FlatCap); pen.setColor(colors.count() ? colors[0] : QColor(255, 255, 255)); painter.setPen(pen); painter.translate(center.x(), center.y()); painter.scale(xRatio, yRatio); if (chanCount >= 2) { for (int i = 0; i + 1 < chanCount; i += 2) { float* data1 = _data + maxFrames * i; float* data2 = _data + maxFrames * (i + 1); QPainterPath path; path.moveTo(data1[0], data2[0]); for (int f = 1; f < frameCount; ++f) path.lineTo(data1[f], data2[f]); pen.setColor(i < colors.count() ? colors[i] : QColor(255, 255, 255)); painter.setPen(pen); painter.drawPath(path); } } else { float* data1 = _data; QPainterPath path; path.moveTo(data1[0], 0.f); for (int f = 1; f < frameCount; ++f) path.lineTo(data1[f], 0.f); painter.drawPath(path); } } void QcScopeShm::connectSharedMemory(int port) { try { server_shared_memory_client* client = new server_shared_memory_client(port); _shm->client = client; qcDebugMsg(1, "Shared memory connected"); } catch (std::exception& e) { _shm->client = 0; qcErrorMsg(QStringLiteral("Cannot connect to shared memory: %1").arg(e.what())); } } void QcScopeShm::initScopeReader(ScopeShm* shm, int index) { shm->reader = shm->client->get_scope_buffer_reader(index); qcDebugMsg(1, QStringLiteral("Initialized scope buffer reader for index %1.").arg(index)); }
10,555
C++
.cpp
284
28.982394
119
0.575683
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,830
QcGraph.cpp
supercollider_supercollider/QtCollider/widgets/QcGraph.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "QcGraph.h" #include "../QcWidgetFactory.h" #include "../style/routines.hpp" #include <QPainter> #include <QPainterPath> #include <QMouseEvent> #include <QApplication> #include <QtCore/qmath.h> #include <cmath> QC_DECLARE_QWIDGET_FACTORY(QcGraph); void QcGraphModel::append(QcGraphElement* e) { if (_elems.count()) { QcGraphElement* prev = _elems.last(); prev->_next = e; e->_prev = prev; } _elems.append(e); Q_EMIT(appended(e)); } void QcGraphModel::removeAt(int i) { QcGraphElement* e = _elems[i]; int ci = _conns.count(); while (ci--) { Connection c = _conns[ci]; if (c.a == e || c.b == e) _conns.removeAt(ci); } if (e->_prev) e->_prev->_next = e->_next; if (e->_next) e->_next->_prev = e->_prev; _elems.removeAt(i); Q_EMIT(removed(e)); delete e; } QcGraph::QcGraph(): QtCollider::Style::Client(this), _defaultThumbSize(QSize(18, 18)), _gridOn(false), _style(DotElements), _drawLines(true), _drawRects(true), _editable(true), _step(0.01), _selectionForm(ElasticSelection), _xOrder(NoOrder), _geometryDirty(false), _lastIndex(-1) { QPalette plt(palette()); setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAttribute(Qt::WA_AcceptTouchEvents); connect(&_model, SIGNAL(removed(QcGraphElement*)), this, SLOT(onElementRemoved(QcGraphElement*))); } QVariantList QcGraph::value() const { QVariantList x; QVariantList y; QList<QcGraphElement*> elems = _model.elements(); Q_FOREACH (QcGraphElement* e, elems) { QPointF val = e->value; x.append(val.x()); y.append(val.y()); } QVariantList values; values.append(QVariant(x)); values.append(QVariant(y)); return values; } QcGraphElement* QcGraph::currentElement() const { return _selection.count() ? _selection.elems.first().elem : 0; } int QcGraph::index() const { QcGraphElement* e = currentElement(); return e ? _model.elements().indexOf(e) : -1; } QVariantList QcGraph::selectionIndexes() const { QVariantList result; int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); if (e->selected) result << i; } return result; } float QcGraph::currentX() const { QcGraphElement* e = currentElement(); return e ? e->value.x() : 0.f; } float QcGraph::currentY() const { QcGraphElement* e = currentElement(); return e ? e->value.y() : 0.f; } void QcGraph::setValue(const QVariantList& list) { if (list.count() != 2) return; QVariantList xList = list[0].toList(); QVariantList yList = list[1].toList(); int newc = qMin(xList.count(), yList.count()); if (!newc) return; int c = _model.elementCount(); while (c > newc) { --c; _model.removeAt(c); } int i; for (i = 0; i < newc; ++i) { QPointF val(xList[i].toFloat(), yList[i].toFloat()); if (i < c) { QcGraphElement* e = _model.elementAt(i); setValue(e, val); } else { QcGraphElement* e = new QcGraphElement(_defaultThumbSize); setValue(e, val); _model.append(e); } } if (newc) ensureOrder(); _geometryDirty = true; update(); } void QcGraph::setStrings(const QVariantList& list) { int strc = list.count(); int c = _model.elementCount(); int i; for (i = 0; i < c && i < strc; ++i) { QcGraphElement* e = _model.elementAt(i); e->text = list[i].toString(); } update(); } void QcGraph::setCurves(const QVariantList& curves) { for (int i = 0; i < curves.size() && i < _model.elementCount(); ++i) { const QVariant& data = curves[i]; QcGraphElement::CurveType type; double curvature; if (data.type() == QVariant::Int) { type = (QcGraphElement::CurveType)data.toInt(); curvature = 0.0; } else { type = QcGraphElement::Curvature; curvature = data.toDouble(); } _model.elementAt(i)->setCurveType(type, curvature); } update(); } void QcGraph::setCurves(double curvature) { Q_FOREACH (QcGraphElement* e, _model.elements()) e->setCurveType(QcGraphElement::Curvature, curvature); update(); } void QcGraph::setCurves(int typeId) { QcGraphElement::CurveType type = (QcGraphElement::CurveType)typeId; Q_FOREACH (QcGraphElement* e, _model.elements()) e->setCurveType(type); update(); } void QcGraph::setStringAt(int i, const QString& str) { int c = _model.elementCount(); if (i >= 0 && i < c) { QcGraphElement* e = _model.elementAt(i); e->text = str; update(); } } void QcGraph::connectElements(int src, QVariantList targets) { int c = _model.elementCount(); if (src < 0 || src >= c) return; Q_FOREACH (const QVariant& var, targets) { int trg = var.toInt(); if (trg < 0 || trg >= c) continue; _model.connect(src, trg); } update(); } void QcGraph::setIndex(int i) { select(i); } void QcGraph::select(int i, bool exclusive) { if (i >= 0 && i < _model.elementCount()) { if (exclusive) setAllDeselected(); setIndexSelected(i, true); update(); } } void QcGraph::deselect(int i) { if (i >= 0 && i < _model.elementCount()) { setIndexSelected(i, false); update(); } } void QcGraph::deselectAll() { setAllDeselected(); } void QcGraph::setCurrentX(float f) { QcGraphElement* e = currentElement(); if (!e) return; QPointF val = e->value; val.setX(f); if (_xOrder != NoOrder) orderRestrictValue(e, val, true); else restrictValue(val); e->value = val; update(); } void QcGraph::setCurrentY(float f) { QcGraphElement* e = currentElement(); if (!e) return; QPointF val = e->value; val.setY(f); if (_xOrder != NoOrder) orderRestrictValue(e, val, true); else restrictValue(val); e->value = val; update(); } void QcGraph::setThumbSize(int s) { QSize size(s, s); _defaultThumbSize = size; int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); e->size = size; } _largestThumbSize = size; _geometryDirty = false; update(); } void QcGraph::setThumbWidth(int w) { _defaultThumbSize.setWidth(w); int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); e->size.setWidth(w); } // For backward compatibility, switch to style that supports // different thumb width and height: _style = RectElements; _largestThumbSize.setWidth(w); update(); } void QcGraph::setThumbHeight(int h) { _defaultThumbSize.setHeight(h); int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); e->size.setHeight(h); } // For backward compatibility, switch to style that supports // different thumb width and height: _style = RectElements; _largestThumbSize.setHeight(h); update(); } void QcGraph::setThumbSizeAt(int i, int s) { if (i < 0 || i >= _model.elementCount()) return; _model.elementAt(i)->size = QSize(s, s); _geometryDirty = true; update(); } void QcGraph::setThumbWidthAt(int i, int w) { if (i < 0 || i >= _model.elementCount()) return; _model.elementAt(i)->size.setWidth(w); // For backward compatibility, switch to style that supports // different thumb width and height: _style = RectElements; _geometryDirty = true; update(); } void QcGraph::setThumbHeightAt(int i, int h) { if (i < 0 || i >= _model.elementCount()) return; _model.elementAt(i)->size.setHeight(h); // For backward compatibility, switch to style that supports // different thumb width and height: _style = RectElements; _geometryDirty = true; update(); } void QcGraph::setFillColor(const QColor& color) { int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); e->fillColor = color; } update(); } void QcGraph::setFillColorAt(int i, const QColor& color) { int c = _model.elementCount(); if (i >= 0 && i < c) { QcGraphElement* e = _model.elementAt(i); e->fillColor = color; update(); } } void QcGraph::setEditableAt(int i, bool b) { int c = _model.elementCount(); if (i >= 0 && i < c) { QcGraphElement* e = _model.elementAt(i); e->editable = b; } } void QcGraph::setStep(double step) { _step = qMax(0.0, step); if (_model.elementCount()) { ensureOrder(); update(); }; } void QcGraph::setHorizontalOrder(int i) { _xOrder = (Order)i; if (_xOrder != NoOrder) { ensureOrder(); update(); } } void QcGraph::onElementRemoved(QcGraphElement* e) { _selection.elems.removeAll(SelectedElement(e)); } void QcGraph::setAllDeselected() { int c = _model.elementCount(); for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); e->selected = false; } _selection.elems.clear(); } void QcGraph::setIndexSelected(int index, bool select) { Q_ASSERT(index >= 0 && index < _model.elementCount()); // exit early if the element's selection status is already correct QcGraphElement* e = _model.elementAt(index); if (e->selected == select) return; if (select) { e->selected = true; // insert this node into the list of selected elements after selected // nodes with lower indices. Maintains that the list is sorted. int numSelectedNodes = 0; for (int i = 0; i < index; ++i) { if (_model.elementAt(i)->selected) ++numSelectedNodes; } _selection.elems.insert(numSelectedNodes, SelectedElement(e)); // mark this as the last index selected _lastIndex = index; } else { e->selected = false; _selection.elems.removeAll(SelectedElement(e)); } update(); } inline static void qc_graph_round(double& val, double& step, bool& grid) { if (val < 0.0) { val = 0.0; } else if (grid) { double ratio = (val + (step * 0.5) > 1.0) ? qFloor(1.0 / step) : qRound(val / step); val = ratio * step; } else if (val > 1.0) { val = 1.0; } } inline void QcGraph::restrictValue(QPointF& val) { double x = val.x(); double y = val.y(); bool grid = _step > 0.0; qc_graph_round(x, _step, grid); qc_graph_round(y, _step, grid); val.setX(x); val.setY(y); } void QcGraph::orderRestrictValue(QcGraphElement* e, QPointF& val, bool selected) { restrictValue(val); double x0 = e->value.x(); double x = val.x(); if (x == x0) { return; } else if (x < x0) { // new x is smaller, check if not too small; QcGraphElement* prev = e->prev(); if (prev && (selected || !prev->selected) && x < prev->value.x()) val.setX(prev->value.x()); } else { // new x is larger, check if not too large; QcGraphElement* next = e->next(); if (next && (selected || !next->selected) && x > next->value.x()) val.setX(next->value.x()); } } inline void QcGraph::setValue(QcGraphElement* e, const QPointF& pt) { QPointF val(pt); restrictValue(val); e->value = val; } void QcGraph::ensureOrder() { int c = _model.elementCount(); double x_min = 0.0; for (int i = 0; i < c; ++i) { QcGraphElement* e = _model.elementAt(i); QPointF val = e->value; if (_xOrder != NoOrder && val.x() < x_min) val.setX(x_min); setValue(e, val); x_min = e->value.x(); } } void QcGraph::moveFree(QcGraphElement* e, const QPointF& val) { if (!e->editable) return; setValue(e, val); } void QcGraph::moveOrderRestricted(QcGraphElement* e, const QPointF& val) { if (!e->editable) return; QPointF v(val); orderRestrictValue(e, v, true); e->value = v; } void QcGraph::moveSelected(const QPointF& dif, SelectionForm form, bool cached) { int c = _selection.count(); switch (form) { case ElasticSelection: { switch (_xOrder) { case NoOrder: for (int i = 0; i < c; ++i) { SelectedElement& se = _selection.elems[i]; moveFree(se.elem, (cached ? se.moveOrigin : se.elem->value) + dif); } break; case RigidOrder: if (dif.x() <= 0) { for (int i = 0; i < c; ++i) { SelectedElement& se = _selection.elems[i]; moveOrderRestricted(se.elem, (cached ? se.moveOrigin : se.elem->value) + dif); } } else { for (int i = _selection.count() - 1; i >= 0; --i) { SelectedElement& se = _selection.elems[i]; moveOrderRestricted(se.elem, (cached ? se.moveOrigin : se.elem->value) + dif); } } break; } break; } case RigidSelection: { // reduce dif until acceptable by all nodes QPointF d(dif); for (int i = 0; i < c; ++i) { SelectedElement& se = _selection.elems[i]; // if any node in selection is not editable, abort, since // we want to keep the selection form! if (!se.elem->editable) return; QPointF val0 = (cached ? se.moveOrigin : se.elem->value); QPointF val = val0 + d; if (_xOrder == NoOrder) { restrictValue(val); } else { orderRestrictValue(se.elem, val, false); } d = val - val0; } // if no dif left, do not bother moving if (d.isNull()) return; // move all with the new dif for (int i = 0; i < c; ++i) { SelectedElement& se = _selection.elems[i]; if (!se.elem->editable) continue; se.elem->value = (cached ? se.moveOrigin : se.elem->value) + d; } break; } } } void QcGraph::addCurve(QPainterPath& path, QcGraphElement* e1, QcGraphElement* e2) { QcGraphElement::CurveType type = e1->curveType; const QPointF& pt1 = e1->value; const QPointF& pt2 = e2->value; // coefficients for control points of cubic curve // approximating first quarter of sinusoid // technically: y = sin(pi*x/2) over x = [0,1] static const float ax = 1.0 / 3.0; static const float ay = 0.52359877f; // pi/6 static const float bx = 2.0 / 3.0; static const float by = 1.0; switch (type) { case QcGraphElement::Step: path.moveTo(pt1); path.lineTo(pt1.x(), pt2.y()); path.lineTo(pt2); break; case QcGraphElement::Hold: path.moveTo(pt1); path.lineTo(pt1.y(), pt2.y()); path.lineTo(pt2); break; case QcGraphElement::Linear: path.moveTo(pt1); path.lineTo(pt2); break; case QcGraphElement::Quadratic: { path.moveTo(pt1); const qreal x1 = pt1.x(); const qreal x2 = pt2.x(); const qreal y1 = std::sqrt(pt1.y()); const qreal y2 = std::sqrt(pt2.y()); static const int n = 100; const qreal dx = x2 - x1; const qreal dy = y2 - y1; const qreal k = dx != 0.0 ? dy / dx : 0.0; const qreal a = y1 - x1 * k; const qreal kx = dx / n; for (int i = 1; i < n; ++i) { qreal x = i * kx + x1; qreal y = k * x + a; path.lineTo(x, y * y); } path.lineTo(pt2); break; } case QcGraphElement::Cubic: { path.moveTo(pt1); const qreal x1 = pt1.x(); const qreal x2 = pt2.x(); const qreal y1 = std::pow(pt1.y(), qreal(1 / 3.0)); const qreal y2 = std::pow(pt2.y(), qreal(1 / 3.0)); static const int n = 100; const qreal dx = x2 - x1; const qreal dy = y2 - y1; const qreal k = dx != 0.0 ? dy / dx : 0.0; const qreal a = y1 - x1 * k; const qreal kx = dx / n; for (int i = 1; i < n; ++i) { qreal x = i * kx + x1; qreal y = k * x + a; path.lineTo(x, y * y * y); } path.lineTo(pt2); break; } case QcGraphElement::Sine: { // half of difference between end points float dx = (pt2.x() - pt1.x()) * 0.5f; float dy = (pt2.y() - pt1.y()) * 0.5f; // middle point QPointF mid = pt1 + QPointF(dx, dy); path.moveTo(pt1); path.cubicTo(pt1 + QPointF(dx * (1 - bx), dy * (1 - by)), pt1 + QPointF(dx * (1 - ax), dy * (1 - ay)), mid); path.cubicTo(mid + QPointF(dx * ax, dy * ay), mid + QPointF(dx * bx, dy * by), pt2); break; } case QcGraphElement::Welch: { // difference between points float dx = (pt2.x() - pt1.x()); float dy = (pt2.y() - pt1.y()); path.moveTo(pt1); if (dy > 0) path.cubicTo(pt1 + QPointF(dx * ax, dy * ay), pt1 + QPointF(dx * bx, dy * by), pt2); else path.cubicTo(pt1 + QPointF(dx * (1 - bx), dy * (1 - by)), pt1 + QPointF(dx * (1 - ax), dy * (1 - ay)), pt2); break; } case QcGraphElement::Exponential: { // FIXME: find a Bezier curve approximation path.moveTo(pt1); float dy = (pt2.y() - pt1.y()); // prevent NaN, optimize if (pt1.y() <= 0.f || pt2.y() <= 0.f) { path.lineTo(dy < 0 ? QPointF(pt1.x(), pt2.y()) : QPointF(pt2.x(), pt1.y())); path.lineTo(pt2); } else { static const int n = 100; const qreal x1 = pt1.x(); const qreal x2 = pt2.x(); const qreal y1 = pt1.y(); const qreal y2 = pt2.y(); const qreal kx = (x2 - x1) / n; const double ky = y1 != 0.0 ? std::pow(y2 / y1, 1.0 / n) : 1.f; double y = y1; for (int i = 1; i < n; ++i) { qreal x = i * kx + x1; y = y * ky; path.lineTo(x, y); } path.lineTo(pt2); } break; } case QcGraphElement::Curvature: // FIXME: find a Bezier curve approximation path.moveTo(pt1); // prevent NaN double curve = qBound(-100.0, e1->curvature, 100.0); if (std::abs(curve) < 0.0001) { path.lineTo(pt2); } else { float dx = (pt2.x() - pt1.x()); float dy = (pt2.y() - pt1.y()); double denom = 1.0 - exp(curve); const float n = 100.f; for (float ph = 1 / n; ph <= (1 - 1 / n); ph += 1 / n) { double numer = 1.0 - exp(ph * curve); qreal y = pt1.y() + dy * (numer / denom); path.lineTo(pt1.x() + (dx * ph), y); } path.lineTo(pt2); } break; } } QSize QcGraph::drawnElementSize(QcGraphElement* e) { if (_style == DotElements) { int s = qMin(e->size.width(), e->size.height()); return QSize(s, s); } else return e->size; } QRect QcGraph::valueRect() { using namespace QtCollider::Style; if (_geometryDirty) { int w = 0; int h = 0; int c = _model.elementCount(); if (_style == RectElements) { for (int i = 0; i < c; ++i) { QSize s = _model.elementAt(i)->size; w = qMax(w, s.width()); h = qMax(h, s.height()); } } else { for (int i = 0; i < c; ++i) { QSize s = _model.elementAt(i)->size; w = qMax(w, qMin(s.width(), s.height())); } h = w; } _largestThumbSize = QSize(w, h); _geometryDirty = false; } return marginsRect(sunkenContentsRect(rect()), _largestThumbSize).adjusted(1, 1, -1, -1); } QRectF QcGraph::labelRect(QcGraphElement* e, const QPointF& pt, const QRect& bounds, const QFontMetrics& fm) { QRectF textRect(fm.boundingRect(e->text)); QSize sz(drawnElementSize(e)); qreal hnd_w_2 = sz.width() * 0.5; qreal hnd_h_2 = sz.height() * 0.5; textRect.moveBottomLeft(pt + QPointF(hnd_w_2, -hnd_h_2)); if (textRect.y() < bounds.y()) textRect.moveTop(pt.y() + hnd_h_2); if (textRect.right() > bounds.right()) textRect.moveRight(pt.x() - hnd_w_2); return textRect; } void QcGraph::paintEvent(QPaintEvent*) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; using QtCollider::Style::RoundRect; QPainter p(this); const QPalette& plt = palette(); p.setRenderHint(QPainter::Antialiasing, true); RoundRect frame(rect(), 2); drawSunken(&p, plt, frame, background(), hasFocus() ? focusColor() : QColor()); p.setRenderHint(QPainter::Antialiasing, false); QRect contentsRect(valueRect()); // draw grid; p.setPen(gridColor()); p.setBrush(Qt::NoBrush); p.drawRect(contentsRect); if (_gridOn) { float dx = _gridMetrics.x(); float dy = _gridMetrics.y(); float cl = contentsRect.left(); float cr = contentsRect.right(); float ct = contentsRect.top(); float cb = contentsRect.bottom(); if (contentsRect.width() > 0.f && dx > 0.f && dx < 1.f) { dx *= contentsRect.width(); int i = 1; float x; while ((x = i * dx + cl) < cr) { p.drawLine(x, ct, x, cb); ++i; } } if (contentsRect.height() > 0.f && dy > 0.f && dy < 1.f) { dy *= contentsRect.height(); int i = 1; float y; while ((y = cb - i * dy) > ct) { p.drawLine(cl, y, cr, y); ++i; } } } QList<QcGraphElement*> elems = _model.elements(); int c = elems.count(); if (!c) return; const QColor& strokeClr = strokeColor(); QPen pen; pen.setColor(strokeClr); pen.setWidth(0); p.setPen(pen); // draw lines; if (_drawLines) { QPainterPath lines; QList<QcGraphModel::Connection> conns = _model.connections(); if (conns.count()) { Q_FOREACH (QcGraphModel::Connection c, conns) { addCurve(lines, c.a, c.b); } } else { QcGraphElement* e1 = elems[0]; int i; for (i = 1; i < c; ++i) { QcGraphElement* e2 = elems[i]; addCurve(lines, e1, e2); e1 = e2; } } p.save(); p.setRenderHint(QPainter::Antialiasing, true); p.setBrush(Qt::NoBrush); p.translate(contentsRect.x(), contentsRect.y() + contentsRect.height()); p.scale(contentsRect.width(), -contentsRect.height()); p.drawPath(lines); p.restore(); } // draw rects and strings if (_drawRects) { p.setRenderHint(QPainter::Antialiasing, true); QFontMetrics fm(font()); QColor rectColor = plt.color(QPalette::Button).lighter(105); QColor circleColor = rectColor; circleColor.setAlpha(70); QColor dotColor = plt.color(QPalette::Text); const QColor& selectClr = selectionColor(); QRectF rect; QPointF pt; int i; for (i = 0; i < c; ++i) { QcGraphElement* e = elems[i]; rect.setSize(drawnElementSize(e)); pt = Style::pos(e->value, contentsRect); rect.moveCenter(pt.toPoint()); if (_style == DotElements) drawDotElement(e, rect, contentsRect, dotColor, circleColor, strokeClr, selectClr, plt, fm, &p); else drawRectElement(e, rect, rectColor, strokeClr, selectClr, plt, &p); } } } void QcGraph::drawDotElement(QcGraphElement* e, const QRectF& rect, const QRect& bounds, const QColor& dotColor, const QColor& circleColor, const QColor& textColor, const QColor& selectColor, const QPalette& plt, const QFontMetrics& fm, QPainter* p) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; // base Ellipse thumb(rect); drawRaised(p, plt, thumb, circleColor); // marker QRectF r(thumb._rect); qreal wdif = r.width() * 0.3; qreal hdif = r.height() * 0.3; p->setPen(Qt::NoPen); p->setBrush(e->fillColor.isValid() ? e->fillColor : dotColor); p->drawEllipse(r.adjusted(wdif, hdif, -wdif, -hdif)); // selection indicator if (e->selected) { p->setBrush(Qt::NoBrush); p->setPen(selectColor); p->drawEllipse(thumb._rect.adjusted(1, 1, -1, -1)); } // label p->setPen(textColor); QString text = e->text; if (!text.isEmpty()) { QRectF lblRect(labelRect(e, rect.center(), bounds, fm)); p->drawText(lblRect, 0, text); } } void QcGraph::drawRectElement(QcGraphElement* e, const QRectF& rect, const QColor& fillColor, const QColor& textColor, const QColor& selectColor, const QPalette& plt, QPainter* p) { using namespace QtCollider::Style; using QtCollider::Style::RoundRect; // base RoundRect base(rect, 5); drawRaised(p, plt, base, e->fillColor.isValid() ? e->fillColor : fillColor); // selection indicator if (e->selected) { p->setBrush(Qt::NoBrush); p->setPen(selectColor); p->drawRoundedRect(base._rect, 5, 5); } // label p->setPen(textColor); QString text = e->text; if (!text.isEmpty()) { p->drawText(rect, Qt::AlignCenter, text); } } void QcGraph::mousePressEvent(QMouseEvent* ev) { using namespace QtCollider::Style; QList<QcGraphElement*> elems = _model.elements(); int c = elems.count(); if (!c) return; QPointF mpos = ev->pos(); QRectF valueRect(this->valueRect()); QRectF r; int i; for (i = 0; i < c; ++i) { QcGraphElement* e = elems[i]; r.setSize(drawnElementSize(e)); QPointF pt(Style::pos(e->value, valueRect)); r.moveCenter(pt); if (r.contains(mpos)) { if (ev->modifiers() & Qt::ShiftModifier) { setIndexSelected(i, !e->selected); } else { if (!e->selected) { setAllDeselected(); setIndexSelected(i, true); } } _selection.cached = false; if (e->selected) { // if the element that was hit ended up selected // prepare for moving _selection.shallMove = true; _selection.moveOrigin = Style::value(mpos, valueRect); } else { _selection.shallMove = false; } update(); return; } } _selection.shallMove = false; if (!(ev->modifiers() & Qt::ShiftModifier)) { setAllDeselected(); } update(); } void QcGraph::mouseMoveEvent(QMouseEvent* ev) { using namespace QtCollider::Style; if (!ev->buttons()) return; if (!_editable || !_selection.shallMove || !_selection.size()) return; if (!_selection.cached) { int c = _selection.count(); for (int i = 0; i < c; ++i) { SelectedElement& se = _selection.elems[i]; se.moveOrigin = se.elem->value; } _selection.cached = true; } QRectF valueRect(this->valueRect()); QPointF dValue(Style::value(ev->pos(), valueRect)); dValue = dValue - _selection.moveOrigin; moveSelected(dValue, _selectionForm, true); update(); doAction(ev->modifiers()); } void QcGraph::keyPressEvent(QKeyEvent* event) { int mods = event->modifiers(); if (mods & Qt::AltModifier || mods & Qt::ShiftModifier) { // selection mode int c = _model.elementCount(); if (!c) return; switch (event->key()) { case Qt::Key_Right: { // select the index after the last selected one (wrapping) // or extend selection to the right int i = -1; if (_selection.count()) { for (i = c - 1; i >= 0; --i) { if (_model.elementAt(i)->selected) break; } } if (event->modifiers() & Qt::ShiftModifier) { i = qMin(i + 1, c - 1); setIndexSelected(i, true); } else { ++i; if (i >= c) i = 0; setAllDeselected(); setIndexSelected(i, true); } break; } case Qt::Key_Left: { // select the index before the first selected one (wrapping) // or extend selection to the left int i = c; if (_selection.count()) { for (i = 0; i < c; ++i) { if (_model.elementAt(i)->selected) break; } } if (event->modifiers() & Qt::ShiftModifier) { i = qMax(i - 1, 0); setIndexSelected(i, true); } else { --i; if (i < 0) i = c - 1; setAllDeselected(); setIndexSelected(i, true); } break; } default: break; } } else { // editing mode if (!_editable || !_selection.size()) return; QPointF dValue; switch (event->key()) { case Qt::Key_Up: dValue.setY(_step); break; case Qt::Key_Down: dValue.setY(-_step); break; case Qt::Key_Right: dValue.setX(_step); break; case Qt::Key_Left: dValue.setX(-_step); break; default: return; } moveSelected(dValue, _selectionForm, false); update(); doAction(event->modifiers()); } } void QcGraph::doAction(Qt::KeyboardModifiers mods) { Qt::KeyboardModifier ctrlMod = #ifdef Q_OS_MAC Qt::MetaModifier; #else Qt::ControlModifier; #endif if (mods & ctrlMod) Q_EMIT(metaAction()); else Q_EMIT(action()); }
32,038
C++
.cpp
984
24.67378
120
0.547184
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,831
filestream.cpp
supercollider_supercollider/QtCollider/widgets/soundfileview/filestream.cpp
/************************************************************************ * * Copyright 2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "view.hpp" #include <limits> SoundFileStream::SoundFileStream(): _data(0), _dataSize(0), _dataOffset(0) {} SoundFileStream::SoundFileStream(SNDFILE* sf, const SF_INFO& info, sf_count_t b, sf_count_t d): _data(0) { load(sf, info, b, d); } SoundFileStream::~SoundFileStream() { delete[] _data; } void SoundFileStream::load(SNDFILE* sf, const SF_INFO& info, sf_count_t beg, sf_count_t dur) { delete[] _data; _dataOffset = beg; _dataSize = dur; _data = new float[_dataSize * info.channels]; sf_seek(sf, _dataOffset, SEEK_SET); _dataSize = sf_readf_float(sf, _data, _dataSize); _ch = info.channels; _beg = _dataOffset; _dur = _dataSize; } bool SoundFileStream::integrate(int ch, double f_beg, double f_dur, float* minBuffer, float* maxBuffer, float* sumBuf, float* sum2Buf, int bufferSize) { bool ok = _data != 0 && ch < channels() && (f_beg >= beginning()) && (f_beg + f_dur <= beginning() + duration()); if (!ok) return false; double fpu = f_dur / bufferSize; double f_pos = f_beg - _dataOffset; double f_pos_max = _dataSize; int i; for (i = 0; i < bufferSize; ++i) { int data_pos = floor(f_pos); // increment position // slower, but error-proof: // f_pos = (double)(i+1) / width() * f_dur + f_beg; // the following is a faster variant, but floating point operations are fallible, // so we need to make sure we stay within the constraints of f_dur; double f_pos1 = f_pos + fpu; if (f_pos1 > f_pos_max) f_pos1 = f_pos_max; int frame_count = ceil(f_pos1) - data_pos; float frac0 = data_pos + 1.f - f_pos; float frac1 = f_pos1 + 1.f - ceil(f_pos1); // get min, max and sum float* samples = _data + (data_pos * channels()) + ch; float min = std::numeric_limits<float>::max(); float max = std::numeric_limits<float>::lowest(); float sum = 0.f; float sum2 = 0.f; int f; // frame for (f = 0; f < frame_count; ++f, samples += channels()) { // TODO should we overlap min-max or not here? float sample = *samples; float frac; if (f == 0) frac = frac0; else if (f == frame_count - 1) frac = frac1; else frac = 1.0; if (sample < min) min = sample; if (sample > max) max = sample; sum += sample * frac; sum2 += sample * sample * frac; } minBuffer[i] = min; maxBuffer[i] = max; sumBuf[i] = sum; sum2Buf[i] = sum2; f_pos = f_pos1; } return true; } bool SoundFileStream::displayData(int ch, double f_beg, double f_dur, float* minBuffer, float* maxBuffer, float* minRMS, float* maxRMS, int bufferSize) { bool ok = _data != 0 && ch < channels() && (f_beg >= beginning()) && (f_beg + f_dur <= beginning() + duration()); if (!ok) return false; double fpu = f_dur / bufferSize; double f_pos = f_beg - _dataOffset; double f_pos_max = _dataSize; float min = std::numeric_limits<float>::max(); float max = std::numeric_limits<float>::lowest(); int i; for (i = 0; i < bufferSize; ++i) { int data_pos = floor(f_pos); // increment position // slower, but error-proof: // f_pos = (double)(i+1) / width() * f_dur + f_beg; // the following is a faster variant, but floating point operations are fallible, // so we need to make sure we stay within the constraints of f_dur; double f_pos1 = f_pos + fpu; if (f_pos1 > f_pos_max) f_pos1 = f_pos_max; int frame_count = ceil(f_pos1) - data_pos; float frac0 = data_pos + 1.f - f_pos; float frac1 = f_pos1 + 1.f - ceil(f_pos1); // get min, max and sum float* samples = _data + (data_pos * channels()) + ch; float sum = 0.f; float sum2 = 0.f; int f; // frame for (f = 0; f < frame_count; ++f, samples += channels()) { // TODO should we overlap min-max or not here? float sample = *samples; float frac; if (f == 0) frac = frac0; else if (f == frame_count - 1) frac = frac1; else frac = 1.0; if (sample < min) min = sample; if (sample > max) max = sample; sum += sample * frac; sum2 += sample * sample * frac; } double n = fpu; double avg = sum / n; double stdDev = std::sqrt(std::abs((sum2 - (sum * avg)) / n)); minBuffer[i] = min; maxBuffer[i] = max; minRMS[i] = avg - stdDev; maxRMS[i] = avg + stdDev; f_pos = f_pos1; min = maxBuffer[i]; max = minBuffer[i]; } return true; } float* SoundFileStream::rawFrames(int ch, sf_count_t b, sf_count_t d, bool* interleaved) { if (ch > channels() || b < _dataOffset || b + d > _dataOffset + _dataSize) return 0; *interleaved = true; sf_count_t offset = (b - _dataOffset) * channels() + ch; return (_data + offset); }
6,296
C++
.cpp
158
31.670886
120
0.546662
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,832
view.cpp
supercollider_supercollider/QtCollider/widgets/soundfileview/view.cpp
/************************************************************************ * * Copyright 2010-2012 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "view.hpp" #include "../../QcWidgetFactory.h" #include <QGridLayout> #include <QPainter> #include <QPainterPath> #include <QApplication> #include <QPaintEvent> #include <QCursor> #include <climits> #include <cmath> #include <cstring> QC_DECLARE_QWIDGET_FACTORY(QcWaveform); const int kMaxRawFrames = 300000; const int kMaxFramesPerCacheUnit = 128; QcWaveform::QcWaveform(QWidget* parent): QWidget(parent), sf(0), _rangeBeg(0), _rangeDur(0), _rangeEnd(0), _cache(0), _curSel(0), _showCursor(false), _cursorPos(0), _cursorEditable(true), _showGrid(true), _gridResolution(1.0), _gridOffset(0.0), _beg(0.0), _dur(0.0), _yZoom(1.f), _yOffset(0.f), _spacing(0.1f), pixmap(0), _bkgColor(QColor(0, 0, 0)), _peakColor(QColor(242, 178, 0)), _rmsColor(QColor(255, 255, 0)), _cursorColor(QColor(255, 0, 0)), _gridColor(QColor(100, 100, 200)), dirty(false), _drawWaveform(true), _drawRMS(true), // _antialiasing(false), //TODO _drawsCenterLine(true), _drawsBoundingLines(true) { memset(&sfInfo, 0, sizeof(SF_INFO)); setFocusPolicy(Qt::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setAttribute(Qt::WA_OpaquePaintEvent, true); } QcWaveform::~QcWaveform() { delete _cache; delete pixmap; if (sf) sf_close(sf); } void QcWaveform::load(const QString& filename) { qcDebugMsg(1, "QcWaveform::load( filename )"); load(filename, 0, 0, true); } void QcWaveform::load(const QString& filename, int beg, int dur) { qcDebugMsg(1, "QcWaveform::load( filename, beg, dur )"); load(filename, beg, dur, false); } static SNDFILE* sndfileOpenQString(const QString& filename, int mode, SF_INFO* info) { #ifdef _WIN32 auto name = filename.toStdWString(); #else auto name = filename.toStdString(); #endif // _WIN32 return sndfileOpen(name.c_str(), mode, info); } // Negative dur is considered a failure, otherwise we could use dur == -1 to mean "load the whole file." void QcWaveform::load(const QString& filename, int beg, int dur, bool allFrames) { SF_INFO new_info; memset(&new_info, 0, sizeof(SF_INFO)); SNDFILE* new_sf = sndfileOpenQString(filename, SFM_READ, &new_info); if (!new_sf) { qcErrorMsg(QStringLiteral("Could not open soundfile: ") + filename); return; } dur = allFrames ? new_info.frames : dur; doLoad(new_sf, new_info, beg, dur); } void QcWaveform::load(const QVector<double>& data, int offset, int ch, int sr) { qcDebugMsg(1, "QcWaveform::load( data, offset, channels )"); if (ch < 1) { qcWarningMsg("QSoundFileView: invalid number of channels!"); return; } int ns = data.count(); int nf = ns / ch; if (nf * ch != ns) { qcWarningMsg("QSoundFileView: size of data not a multiple of channel count!"); return; } if (offset < 0 || nf - offset < 1) { qcWarningMsg("QSoundFileView: invalid range of data!"); return; } delete _cache; if (sf) sf_close(sf); sf = 0; SF_INFO new_info; memset(&new_info, 0, sizeof(SF_INFO)); new_info.channels = ch; new_info.samplerate = sr; sfInfo = new_info; _beg = _rangeBeg = 0; _dur = _rangeDur = _rangeEnd = nf - offset; updateFPP(); _cache = new SoundCacheStream(); connect(_cache, SIGNAL(loadingDone()), this, SIGNAL(loadingDone())); connect(_cache, SIGNAL(loadingDone()), this, SLOT(redraw())); _cache->load(data, _rangeDur, offset, ch); } void QcWaveform::allocate(int frames, int ch, int sr) { if (ch < 1) { qcWarningMsg("QSoundFileView: invalid number of channels!"); return; } delete _cache; if (sf) sf_close(sf); sf = 0; SF_INFO new_info; memset(&new_info, 0, sizeof(SF_INFO)); new_info.channels = ch; new_info.samplerate = sr; sfInfo = new_info; _beg = _rangeBeg = 0; _dur = _rangeDur = _rangeEnd = frames; updateFPP(); _cache = new SoundCacheStream(); _cache->allocate(frames, ch); redraw(); } void QcWaveform::write(const QVector<double>& data, int offset) { if (sf) { qcWarningMsg("QSoundFileView: can not write data while displaying a sound file!"); return; } if (!_cache || !_cache->ready()) { qcWarningMsg("QSoundFileView: can not write data; memory has not been allocated yet!"); return; } int ch = sfInfo.channels; int ns = data.size(); int nf = ns / ch; if (nf * ch != ns) { qcWarningMsg("QSoundFileView: can not write data; size not a multiple of channels!"); return; } if (offset < 0 || offset + nf > _rangeEnd) { qcWarningMsg("QSoundFileView: can not write data; either offset is wrong or data size is too large."); return; } _cache->write(data, offset, nf); redraw(); } void QcWaveform::doLoad(SNDFILE* new_sf, const SF_INFO& new_info, sf_count_t beg, sf_count_t dur) { // check beginning and duration validity if (beg < 0 || dur < 1 || beg + dur > new_info.frames) { qcErrorMsg("Invalid beginning and/or duration."); sf_close(new_sf); return; } // cleanup previous state // NOTE we have to delete SoundCacheStream before closing the soundfile, as it might be still // loading it // TODO: should SoundCacheStream open the soundfile on its own? delete _cache; if (sf) sf_close(sf); sf = new_sf; sfInfo = new_info; _beg = _rangeBeg = beg; _dur = _rangeDur = dur; _rangeEnd = _rangeBeg + _rangeDur; updateFPP(); _cache = new SoundCacheStream(); connect(_cache, SIGNAL(loadProgress(int)), this, SIGNAL(loadProgress(int))); connect(_cache, SIGNAL(loadProgress(int)), this, SLOT(update())); connect(_cache, SIGNAL(loadingDone()), this, SIGNAL(loadingDone())); connect(_cache, SIGNAL(loadingDone()), this, SLOT(redraw())); _cache->load(sf, sfInfo, beg, dur, kMaxFramesPerCacheUnit, kMaxRawFrames); redraw(); } float QcWaveform::loadProgress() { return _cache ? _cache->loadProgress() : 1.f; } float QcWaveform::zoom() { // NOTE We have limited _rangeDur to 1 minimum. return _dur / _rangeDur; } float QcWaveform::xZoom() { return (sfInfo.samplerate ? _dur / sfInfo.samplerate : 0); } float QcWaveform::yZoom() { return _yZoom; } float QcWaveform::yOffset() { return _yOffset; } float QcWaveform::spacing() { return _spacing; } QVariantList QcWaveform::selections() const { QVariantList slist; for (int i = 0; i < 64; ++i) { slist << QVariant(selection(i)); } return slist; } void QcWaveform::setCurrentSelection(int i) { if (i < 0 || i > 63) return; _curSel = i; update(); } QVariantList QcWaveform::selection(int i) const { QVariantList list; if (i < 0 || i > 63) return list; const Selection& s = _selections[i]; list << QVariant(static_cast<int>(s.start - _rangeBeg)); list << QVariant(static_cast<int>(s.size)); return list; } void QcWaveform::setSelection(int i, sf_count_t a, sf_count_t b) { if (i < 0 || i > 63) return; Selection& s = _selections[i]; s.start = qMin(a, b); s.size = qMax(a, b) - s.start; update(); } void QcWaveform::setSelection(int i, QVariantList list) { if (list.count() < 2) return; sf_count_t start = list[0].toInt() + _rangeBeg; sf_count_t end = start + list[1].toInt(); setSelection(i, start, end); } void QcWaveform::setSelectionStart(int i, sf_count_t frame) { if (i < 0 || i > 63) return; Selection& s = _selections[i]; sf_count_t frame2 = s.start + s.size; s.start = qMin(frame, frame2); s.size = qMax(frame, frame2) - s.start; update(); } void QcWaveform::setSelectionEnd(int i, sf_count_t frame) { if (i < 0 || i > 63) return; Selection& s = _selections[i]; sf_count_t frame2 = s.start; s.start = qMin(frame, frame2); s.size = qMax(frame, frame2) - s.start; update(); } void QcWaveform::setSelectionEditable(int i, bool editable) { if (i < 0 || i > 63) return; _selections[i].editable = editable; update(); } void QcWaveform::setSelectionColor(int i, const QColor& c) { if (i < 0 || i > 63) return; _selections[i].color = c; update(); } QVariantList QcWaveform::waveColors() const { QVariantList clist; Q_FOREACH (QColor clr, _waveColors) clist << QVariant(clr); return clist; } void QcWaveform::setWaveColors(const QVariantList& list) { _waveColors.clear(); Q_FOREACH (const QVariant& var, list) _waveColors << var.value<QColor>(); redraw(); } void QcWaveform::zoomTo(double z) { z = qMax(0.0, qMin(1.0, z)); _dur = qMax(_rangeDur * z, 1.0); // printf("dur: %Li view: %Li\n", sfInfo.frames, _dur); if (_beg + _dur > _rangeEnd) _beg = _rangeEnd - _dur; updateFPP(); redraw(); } void QcWaveform::zoomBy(double factor) { zoomTo(zoom() * factor); } void QcWaveform::zoomAllOut() { _beg = _rangeBeg; _dur = _rangeDur; updateFPP(); redraw(); } void QcWaveform::scrollTo(double startFrame) { _beg = qBound((double)_rangeBeg, startFrame, _rangeEnd - _dur); redraw(); } void QcWaveform::scrollBy(double f) { scrollTo(_beg + f); } float QcWaveform::scrollPos() { double scrollRange = _rangeDur - _dur; return scrollRange > 0.0 ? (_beg - _rangeBeg) / scrollRange : 0.f; } void QcWaveform::setScrollPos(double fraction) { scrollTo(fraction * (_rangeDur - _dur) + _rangeBeg); } void QcWaveform::scrollToStart() { scrollTo(_rangeBeg); } void QcWaveform::scrollToEnd() { scrollTo(_rangeEnd - _dur); } void QcWaveform::setXZoom(double seconds) { // NOTE We have limited _rangeDur to 1 minimum. double frac = seconds * sfInfo.samplerate / _rangeDur; zoomTo(frac); } void QcWaveform::setYZoom(double factor) { _yZoom = factor; redraw(); } void QcWaveform::setYOffset(double offset) { _yOffset = offset; redraw(); } void QcWaveform::setSpacing(double factor) { _spacing = qBound(0.0, factor, 1.0); redraw(); } void QcWaveform::zoomSelection(int i) { if (i < 0 || i > 63) return; Selection& s = _selections[i]; if (s.start >= _rangeEnd || s.size < 1 || s.start + s.size <= _rangeBeg) return; _beg = qMax(s.start, _rangeBeg); double end = qMin(s.start + s.size, _rangeEnd); _dur = end - _beg; // clear the selection s.size = 0; updateFPP(); redraw(); } void QcWaveform::resizeEvent(QResizeEvent*) { delete pixmap; pixmap = new QPixmap(size()); updateFPP(); redraw(); } void QcWaveform::paintEvent(QPaintEvent* ev) { Q_ASSERT(pixmap != 0); QPainter p(this); // if loading draw progress if (_cache && _cache->loading()) { QRect r(rect()); p.fillRect(r, QColor(100, 100, 100)); r.setRight(r.right() * _cache->loadProgress() / 100); p.fillRect(r, QColor(0, 0, 0)); p.setPen(QColor(255, 255, 255)); QTextOption opt; opt.setAlignment(Qt::AlignCenter); p.drawText(rect(), "loading...", opt); return; } p.fillRect(rect(), _bkgColor); // draw waveform on pixmap if (_drawWaveform && dirty) { draw(pixmap, 0, width(), _beg, _dur); dirty = false; } // draw time grid if (_showGrid && sfInfo.samplerate > 0 && _gridResolution > 0.f) { p.save(); // Since _gridResolution and _gridOffset are in seconds, scale using // duration in seconds. double dur_in_secs = _dur / sfInfo.samplerate; p.setPen(Qt::NoPen); p.setBrush(_gridColor); p.scale((double)width() / dur_in_secs, 1.0); // Wrap the offset to (-100%, 100%) of the grid resolution. Subtract by // beg_in_secs to account for zoom+timeshift. double beg_in_secs = _beg / sfInfo.samplerate; double offset = std::fmod(_gridOffset - beg_in_secs, _gridResolution * 2); // Catch the case where the grid is [50% - 100%) offset from the start // in order to draw the portion off the left side of the view. if (offset > _gridResolution) offset -= _gridResolution * 2; while (offset < dur_in_secs) { QRectF r(offset, 0, _gridResolution, height()); p.drawRect(r); offset += _gridResolution * 2; } p.restore(); } // draw selections p.save(); p.scale((double)width() / _dur, 1.0); p.translate(_beg * -1.0, 0.0); p.setPen(Qt::NoPen); int i; for (i = 0; i < 64; ++i) { const Selection& s = _selections[i]; if (s.size > 0) { QRectF r(s.start, 0, s.size, height()); p.setBrush(s.color); p.drawRect(r); } } p.restore(); // paste the waveform pixmap on screen if (_drawWaveform) p.drawPixmap(ev->rect(), *pixmap, ev->rect()); // draw cursor if (_showCursor && _cursorPos >= _beg && _cursorPos < _beg + _dur) { double cursorX = (_cursorPos - _beg) / _fpp; p.setPen(_cursorColor); p.drawLine(QLineF(cursorX, 0, cursorX, height())); } } void QcWaveform::keyPressEvent(QKeyEvent* ev) { if (ev->key() == Qt::Key_Shift && _dragAction == Navigate) { _dragPoint = mapFromGlobal(QCursor::pos()); _dragData2 = zoom(); } else ev->ignore(); } void QcWaveform::mousePressEvent(QMouseEvent* ev) { _dragAction = NoDragAction; _dragPoint = ev->pos(); _dragFrame = ev->pos().x() * _fpp + _beg; Qt::KeyboardModifiers mods = ev->modifiers(); Qt::MouseButton btn = ev->button(); #ifdef Q_OS_MAC Qt::KeyboardModifier CTRL = Qt::MetaModifier; #else Qt::KeyboardModifier CTRL = Qt::ControlModifier; #endif if (btn == Qt::LeftButton) { if ((mods & Qt::ShiftModifier) && (mods & CTRL)) { _dragFrame = _selections[_curSel].start; _dragAction = MoveSelection; } else if (mods & Qt::ShiftModifier) { _dragAction = Select; const Selection& s = _selections[_curSel]; if (_dragFrame < s.start + (s.size * 0.5)) { setSelectionStart(_curSel, _dragFrame); _dragFrame = s.start + s.size; } else { setSelectionEnd(_curSel, _dragFrame); _dragFrame = s.start; } Q_EMIT(action()); } else { if (!(mods & CTRL)) { _dragAction = Select; _selections[_curSel].start = _dragFrame; _selections[_curSel].size = 0; update(); Q_EMIT(action()); } if (_cursorEditable) { _cursorPos = _dragFrame; if (mods & CTRL) _dragAction = MoveCursor; update(); Q_EMIT(metaAction()); } } } else if (btn == Qt::RightButton) { _dragAction = Navigate; _dragData = ev->pos().x() * _fpp + _beg; _dragData2 = zoom(); } } void QcWaveform::mouseDoubleClickEvent(QMouseEvent*) { setSelection(_curSel, _rangeBeg, _rangeEnd); Q_EMIT(action()); } void QcWaveform::mouseMoveEvent(QMouseEvent* ev) { if (!ev->buttons()) return; if (_dragAction == Navigate) { Qt::KeyboardModifiers mods = ev->modifiers(); if (mods & Qt::ShiftModifier) { double factor = pow(2, (ev->pos().y() - _dragPoint.y()) * 0.008); // zoom to the initial zoom times the factor based on distance from initial position zoomTo(_dragData2 * factor); } // scroll to the clicked frame minus the current mouse position in frames // _fpp has been adjusted by zooming scrollTo(_dragData - (ev->pos().x() * _fpp)); } else if (_dragAction == Select) { sf_count_t frame = qBound(0, ev->pos().x(), width()) * _fpp + _beg; setSelection(_curSel, _dragFrame, frame); update(); Q_EMIT(action()); } else if (_dragAction == MoveSelection) { double dpos = ev->pos().x() - _dragPoint.x(); Selection& s = _selections[_curSel]; s.start = _dragFrame + (dpos * _fpp); s.start = qBound(_rangeBeg, s.start, _rangeEnd - s.size); update(); Q_EMIT(action()); } else if (_dragAction == MoveCursor) { _cursorPos = qBound(0, ev->pos().x(), width()) * _fpp + _beg; update(); Q_EMIT(metaAction()); } } void QcWaveform::rebuildCache(int maxFPU, int maxRawFrames) {} void QcWaveform::draw(QPixmap* pix, int x, int width, double f_beg, double f_dur) { // FIXME anomaly: when _fpp reaching 1.0 rms can go outside min-max! pix->fill(QColor(0, 0, 0, 0)); QPainter p(pix); // if( _antialiasing ) p.setRenderHint( QPainter::Antialiasing ); //TODO if (!_cache || !_cache->ready()) return; // check for sane situation: if (f_beg < _rangeBeg || f_beg + f_dur > _rangeEnd) return; // data indexes sf_count_t i_beg = floor(f_beg); // data beginning; sf_count_t i_count = ceil(f_beg + f_dur) - i_beg; // data count; bool haveOneMore; if (i_beg + i_count < _rangeEnd) { ++i_count; haveOneMore = true; } else { haveOneMore = false; } // data source - choose according to horiz. zoom (data-display resolution) bool canUseCache = _fpp < 1.0 ? _cache->fpu() == 1.0 : _fpp >= _cache->fpu(); SoundStream* soundStream; SoundFileStream sfStream; if (canUseCache) { qcDebugMsg(2, QStringLiteral("using cache")); soundStream = _cache; } else if (sf) { qcDebugMsg(2, QStringLiteral("using file")); soundStream = &sfStream; sfStream.load(sf, sfInfo, i_beg, i_count); } else { qcWarningMsg("QSoundFileView: can't paint waveform: view resolution exceeds data cache resolution," " and soundfile is not given."); return; } // geometry float spacing = pix->height() * _spacing / (float)sfInfo.channels; float chHeight = pix->height() * (1.0f - _spacing) / (float)sfInfo.channels; float yOffsetPx = -chHeight / 2.0f * _yOffset; float yScale = -chHeight / 2.0f * _yZoom; // initial painter setup QPen minMaxPen; QPen rmsPen; minMaxPen.setWidth(0); rmsPen.setWidth(0); float halfChH = chHeight * 0.5; float halfChHScaled = halfChH * _yZoom; p.translate(0.f, halfChH + (spacing / 2.0f) + yOffsetPx); int waveColorN = _waveColors.count(); int ch; for (ch = 0; ch < soundStream->channels(); ++ch) { if (ch < waveColorN && _waveColors[ch].isValid()) { QColor clr(_waveColors[ch]); rmsPen.setColor(_rmsColor); minMaxPen.setColor(clr); } else { rmsPen.setColor(_rmsColor); minMaxPen.setColor(_peakColor); } if (_drawsCenterLine) { // draw center line p.setPen(QColor(90, 90, 90)); p.drawLine(x, 0, x + width, 0); } if (_drawsBoundingLines) { // draw bounding lines p.setPen(QColor(100, 100, 100)); p.drawLine(x, halfChHScaled, x + width, halfChHScaled); p.drawLine(x, -halfChHScaled, x + width, -halfChHScaled); } p.save(); p.scale(1.f, yScale); if (_fpp > 1.0) { // draw min-max regions and RMS float* minBuffer = (float*)alloca(width * sizeof(float)); float* maxBuffer = (float*)alloca(width * sizeof(float)); ; float* minRMS = (float*)alloca(width * sizeof(float)); ; float* maxRMS = (float*)alloca(width * sizeof(float)); ; bool ok = soundStream->displayData(ch, f_beg, f_dur, minBuffer, maxBuffer, minRMS, maxRMS, width); Q_ASSERT(ok); int rmsAlpha = rmsPen.color().alpha(); int i; for (i = 0; i < width; ++i) { float min = minBuffer[i]; float max = maxBuffer[i]; int minMaxPxDiff = int((max - min) * -yScale); if (minMaxPxDiff != 0) { p.setPen(minMaxPen); p.drawLine(QPointF(x + i, min), QPointF(x + i, max)); if (_drawRMS && rmsAlpha > 0 && minMaxPxDiff > 4) { if (_fpp > _rmsMaxFpp) { p.setPen(rmsPen); p.drawLine(QPointF(x + i, minRMS[i]), QPointF(x + i, maxRMS[i])); } else { if (_fpp > _rmsMinFpp) { QColor thisColor = rmsPen.color(); thisColor.setAlpha(rmsAlpha * (_fpp - _rmsMinFpp) / (_rmsMaxFpp - _rmsMinFpp)); rmsPen.setColor(thisColor); p.setPen(rmsPen); p.drawLine(QPointF(x + i, minRMS[i]), QPointF(x + i, maxRMS[i])); } } } } else { p.setPen(minMaxPen); p.drawPoint(QPointF(x + i, min)); } } } else { // draw lines between actual values qreal ppf = 1.0 / _fpp; qreal dx = (i_beg - f_beg) * ppf; bool interleaved = false; float* data = soundStream->rawFrames(ch, i_beg, i_count, &interleaved); Q_ASSERT(data != 0); int step = interleaved ? soundStream->channels() : 1; QPainterPath path; if (i_count) { QPointF pt(dx, (qreal)*data); path.moveTo(pt); } int f; // frame for (f = 1; f < i_count; ++f) { data += step; QPointF pt(f * ppf + dx, (qreal)*data); path.lineTo(pt); } if (i_count && !haveOneMore) { path.lineTo(QPointF(f * ppf + dx, (qreal)*data)); } p.setPen(minMaxPen); p.drawPath(path); } p.restore(); p.translate(0.f, chHeight + spacing); } }
23,478
C++
.cpp
664
28.192771
111
0.581332
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,834
hacks_x11.cpp
supercollider_supercollider/QtCollider/hacks/hacks_x11.cpp
/************************************************************************ * * adapted from: * wmctrl * A command line tool to interact with an EWMH/NetWM compatible X Window Manager. * * Copyright 2003 Tomas Styblo <tripie@cpan.org> * Copyright 2011 Tim Blechmann (tim@klingt.org) * Copyright 2011 Jakob Leben (jakob.leben@gmail.com) * * This file is part of SuperCollider Qt GUI. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ #include "hacks_x11.hpp" #ifdef Q_WS_X11 # include <stdlib.h> # include <stdio.h> # include <X11/Xlib.h> # include <X11/Xatom.h> # define MAX_PROPERTY_VALUE_LEN 4096 static inline void p_verbose(...) {} # define gchar char # define gboolean bool # define g_malloc (char*)malloc # define g_free free static gchar* get_property(Display* disp, Window win, Atom xa_prop_type, const gchar* prop_name, unsigned long* size) { Atom xa_prop_name; Atom xa_ret_type; int ret_format; unsigned long ret_nitems; unsigned long ret_bytes_after; unsigned long tmp_size; unsigned char* ret_prop; gchar* ret; xa_prop_name = XInternAtom(disp, prop_name, False); /* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage): * * long_length = Specifies the length in 32-bit multiples of the * data to be retrieved. */ if (XGetWindowProperty(disp, win, xa_prop_name, 0, MAX_PROPERTY_VALUE_LEN / 4, False, xa_prop_type, &xa_ret_type, &ret_format, &ret_nitems, &ret_bytes_after, &ret_prop) != Success) { p_verbose("Cannot get %s property.\n", prop_name); return NULL; } if (xa_ret_type != xa_prop_type) { p_verbose("Invalid type of %s property.\n", prop_name); XFree(ret_prop); return NULL; } /* null terminate the result to make string handling easier */ tmp_size = (ret_format / 8) * ret_nitems; ret = g_malloc(tmp_size + 1); memcpy(ret, ret_prop, tmp_size); ret[tmp_size] = '\0'; if (size) { *size = tmp_size; } XFree(ret_prop); return ret; } /*}}}*/ static int client_msg(Display* disp, Window win, const char* msg, /* {{{ */ unsigned long data0, unsigned long data1, unsigned long data2, unsigned long data3, unsigned long data4) { XEvent event; long mask = SubstructureRedirectMask | SubstructureNotifyMask; event.xclient.type = ClientMessage; event.xclient.serial = 0; event.xclient.send_event = True; event.xclient.message_type = XInternAtom(disp, msg, False); event.xclient.window = win; event.xclient.format = 32; event.xclient.data.l[0] = data0; event.xclient.data.l[1] = data1; event.xclient.data.l[2] = data2; event.xclient.data.l[3] = data3; event.xclient.data.l[4] = data4; if (XSendEvent(disp, DefaultRootWindow(disp), False, mask, &event)) { return EXIT_SUCCESS; } else { fprintf(stderr, "Cannot send %s event.\n", msg); return EXIT_FAILURE; } } /*}}}*/ static int activate_window(Display* disp, Window win, /* {{{ */ gboolean switch_desktop) { unsigned long* desktop; /* desktop ID */ if ((desktop = (unsigned long*)get_property(disp, win, XA_CARDINAL, "_NET_WM_DESKTOP", NULL)) == NULL) { if ((desktop = (unsigned long*)get_property(disp, win, XA_CARDINAL, "_WIN_WORKSPACE", NULL)) == NULL) { p_verbose("Cannot find desktop ID of the window.\n"); } } if (switch_desktop && desktop) { if (client_msg(disp, DefaultRootWindow(disp), "_NET_CURRENT_DESKTOP", *desktop, 0, 0, 0, 0) != EXIT_SUCCESS) { p_verbose("Cannot switch desktop.\n"); } } if (desktop) g_free(desktop); client_msg(disp, win, "_NET_ACTIVE_WINDOW", 0, 0, 0, 0, 0); XMapRaised(disp, win); return EXIT_SUCCESS; } /*}}}*/ # undef p_verbose # undef gchar # undef gboolean # undef g_malloc # undef g_free bool raise_window(Display* display, QWidget* win) { Window window = win->winId(); int raised_via_xlib_error = XRaiseWindow(display, window); if (raised_via_xlib_error == 0) return true; int raised_via_ewmh_error = activate_window(display, window, true); return raised_via_ewmh_error == 0; } #endif
5,052
C++
.cpp
132
33.204545
119
0.630364
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,835
ProxyStyle.cpp
supercollider_supercollider/QtCollider/style/ProxyStyle.cpp
#include "ProxyStyle.hpp" #include "../QcApplication.h" #include <QtGlobal> #include <QStyleOptionSlider> #include <QPainter> #ifdef SC_USE_QTWEBENGINE # include <QWebEngineView> #endif #ifdef Q_OS_MAC # include "../hacks/hacks_mac.hpp" #endif using namespace QtCollider; static bool AlwaysShowScrollbars() { #if defined(Q_OS_MAC) return QtCollider::Mac::AlwaysShowScrollbars(); #elif defined(Q_OS_X11) return true; #elif defined(Q_OS_WIN) return true; #else return true; #endif }; void ProxyStyle::drawComplexControl(ComplexControl ctrl, const QStyleOptionComplex* opt, QPainter* p, const QWidget* w) const { #ifdef SC_USE_QTWEBENGINE // FIXME: this is a workaround for the WebKit bug #104116 (or a variation on it). if (ctrl == QStyle::CC_ScrollBar && qobject_cast<const QWebEngineView*>(w) != 0 && opt->type == QStyleOption::SO_Slider) { // WebKit tries to hide scrollbars, but mistakenly hides QWebView - NULL-ify styleObject to prevent. const QStyleOptionSlider* optSlider = static_cast<const QStyleOptionSlider*>(opt); QStyleOptionSlider opt2(*optSlider); opt2.styleObject = NULL; QProxyStyle::drawComplexControl(ctrl, &opt2, p, w); return; } #endif // SC_USE_QTWEBENGINE if (ctrl == QStyle::CC_ScrollBar && AlwaysShowScrollbars()) { const QStyleOptionSlider* optSlider = static_cast<const QStyleOptionSlider*>(opt); QStyleOptionSlider opt2(*optSlider); opt2.state = State_On; QProxyStyle::drawComplexControl(ctrl, static_cast<const QStyleOptionComplex*>(&opt2), p, w); return; } QProxyStyle::drawComplexControl(ctrl, opt, p, w); } int ProxyStyle::styleHint(StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { switch (hint) { case QStyle::SH_Slider_AbsoluteSetButtons: return Qt::LeftButton; case QStyle::SH_Slider_PageSetButtons: return Qt::NoButton; case QStyle::SH_ScrollBar_Transient: return 1; default: return QProxyStyle::styleHint(hint, option, widget, returnData); } }
2,210
C++
.cpp
59
31.915254
108
0.693964
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,836
slider_style.cpp
supercollider_supercollider/QtCollider/style/slider_style.cpp
#include "style.hpp" #include "routines.hpp" #include "../widgets/QcSlider.h" #include <QPainter> namespace QtCollider { namespace Style { QRect Slider::sc_groove(const QStyleOption* opt, const QcSlider*) { return sunkenContentsRect(opt->rect); } QRect Slider::sc_handle(const QStyleOptionSlider* opt, const QcSlider* s) { QRect contRect(sunkenContentsRect(opt->rect)); double valRange = opt->maximum - opt->minimum; double val = valRange > 0.0 ? (opt->sliderPosition - opt->minimum) / valRange : 0.0; int len = s->handleLength(); QRect r; if (opt->orientation == Qt::Horizontal) { int pos = val * (contRect.width() - len); r.setX(pos + contRect.left()); r.setY(contRect.top()); r.setSize(QSize(len, contRect.height())); } else { int pos = val * (contRect.height() - len); r.setX(contRect.left()); r.setY(contRect.bottom() - pos - len + 1); r.setSize(QSize(contRect.width(), len)); } return r; } void Slider::cc_draw(const QStyleOptionSlider* opt, QPainter* p, const QcSlider* slider) { using QtCollider::Style::Ellipse; using QtCollider::Style::RoundRect; const QPalette& plt = opt->palette; p->save(); p->setRenderHint(QPainter::Antialiasing, true); QRect rGroove = opt->rect; // draw groove RoundRect shGroove(rGroove, 2); QColor baseColor(slider->grooveColor()); QColor focusColor; if (opt->state & QStyle::State_HasFocus) focusColor = slider->focusColor(); drawSunken(p, plt, shGroove, baseColor, focusColor); // geometry QRect rHandle(sc_handle(opt, slider)); // draw handle RoundRect shHandle(rHandle, 2); drawRaised(p, plt, shHandle, plt.color(QPalette::Button).lighter(105)); p->restore(); // draw marker QPen pen(plt.color(QPalette::ButtonText)); pen.setWidth(2); p->setPen(pen); if (opt->orientation == Qt::Horizontal) { qreal center = rHandle.center().x() + 1; QLine line(center, rHandle.top() + 3, center, rHandle.bottom() - 2); p->drawLine(line); pen.setColor(plt.color(QPalette::Light)); } else { qreal center = rHandle.center().y() + 1; QLine line(rHandle.left() + 3, center, rHandle.right() - 2, center); p->drawLine(line); pen.setColor(plt.color(QPalette::Light)); } } } // namespace Style } // namespace QtCollider
2,425
C++
.cpp
63
32.873016
107
0.647887
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,837
style.cpp
supercollider_supercollider/QtCollider/style/style.cpp
#include "style.hpp" #include "routines.hpp" using namespace QtCollider::Style; void StyleImpl::polish(QPalette& p) { _colors[Focus] = p.color(QPalette::Highlight); _colors[Groove] = p.color(QPalette::Window).darker(120); }
235
C++
.cpp
7
31
60
0.733333
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,838
PyrMessage.cpp
supercollider_supercollider/lang/LangSource/PyrMessage.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PyrMessage.h" #include "PyrPrimitiveProto.h" #include "PyrInterpreter.h" #include "PyrPrimitive.h" #include "PyrListPrim.h" #include "PyrSymbol.h" #include "GC.h" #include "PredefinedSymbols.h" #include "PyrObjectProto.h" #include "SCBase.h" #include <optional> #include <csetjmp> #define DEBUGMETHODS 0 #define METHODMETER 0 #ifdef DEBUGMETHODS static constexpr bool DebugMethods = true; #else static constexpr bool DebugMethods = false; #endif #ifdef METHODMETER static constexpr bool MethodMeter = true; #else static constexpr bool MethodMeter = false; #endif #ifdef GC_SANITYCHECK static constexpr bool GCSanityCheckEnabled = true; #else static constexpr bool GCSanityCheckEnabled = false; #endif struct GCSanityChecker { GCSanityChecker(VMGlobals* g, const char* name): g(g), name(name) { if constexpr (GCSanityCheckEnabled) { g->gc->SanityCheck(); CallStackSanity(g, name); } } ~GCSanityChecker() { if constexpr (GCSanityCheckEnabled) { g->gc->SanityCheck(); CallStackSanity(g, name); } } GCSanityChecker(GCSanityChecker&&) = delete; GCSanityChecker(const GCSanityChecker&) = delete; private: VMGlobals* g; const char* name; }; // This MUST be called at the top of the function before the VMGlobals object is altered. void prepForTailCall(VMGlobals* g) { #if TAILCALLOPTIMIZE const int tailCall = g->tailCall; if (tailCall == 1) returnFromMethod(g); else if (tailCall > 0) returnFromBlock(g); #endif } struct ResetTailCall { VMGlobals* g; ~ResetTailCall() { #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } }; PyrMethod** gRowTable; PyrSlot temporaryKeywordStack[temporaryKeywordStackCapacity]; bool gKeywordError = true; extern bool gTraceInterpreter; long cvxUniqueMethods; extern int ivxIdentDict_array; void StoreToImmutableB(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip); void initUniqueMethods() { PyrClass* dummyclass; cvxUniqueMethods = classVarOffset("Object", "uniqueMethods", &dummyclass); } HOT void sendMessageImpl(VMGlobals* g, PyrSymbol* selector, PyrSlot* recvrSlot, PyrClass* classobj, long numArgsPushed, long numKeyArgsPushed) { ResetTailCall reset_tail_call { g }; // General strategy here is to switch on the method type, which add different optimizations. // In cases of redirect and super calls the function to be recursively call, this is implemented with a goto. lookup_again: // The variables classobj and selector are updated when the goto is triggered, causing these to change. auto method = gRowTable[slotRawInt(&classobj->classIndex) + selector->u.index]; auto methodRaw = METHRAW(method); if (slotRawSymbol(&method->name) != selector) { doesNotUnderstand(g, selector, numArgsPushed, numKeyArgsPushed); return; } const auto pushDefaultArgsIfNotEnoughSupplied = [&]() { auto defaultArgs = slotRawObject(&method->prototypeFrame)->slots; std::copy(defaultArgs + numArgsPushed, defaultArgs + methodRaw->numargs, g->sp + 1); g->sp += methodRaw->numargs - numArgsPushed; // fix stack pointer to point to last arg pushed. numArgsPushed = methodRaw->numargs; }; const auto applyKeywords = [&]() { numArgsPushed = keywordFixStack(g, method, methodRaw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; }; // There are multiple types of methods. // The basic is methNormal which goes through executeMethod. // The rest are some form of optimization. switch (methodRaw->methType) { case methNormal: return executeMethod(g, method, numArgsPushed, numKeyArgsPushed); case methReturnSelf: { g->sp -= numArgsPushed - 1; // Remove all args but the receiver. return; } case methReturnLiteral: { g->sp -= numArgsPushed - 1; // Remove all args but the receiver. slotCopy(g->sp, &method->selectors); // Set the first slot to the literal. return; } case methReturnArg: { if (numKeyArgsPushed > 0) applyKeywords(); g->sp -= numArgsPushed - 1; // Remove all args but the receiver. const auto classIndex = methodRaw->specialIndex; // Zero is index of the first argument. if (classIndex < numArgsPushed) slotCopy(g->sp, g->sp + classIndex); else slotCopy(g->sp, &slotRawObject(&method->prototypeFrame)->slots[classIndex]); return; } case methReturnInstVar: { // Return instance variable. g->sp -= numArgsPushed - 1; // Remove all args but the receiver. slotCopy(g->sp, &slotRawObject(recvrSlot)->slots[methodRaw->specialIndex]); return; } case methAssignInstVar: { // Assign to object instance variable g->sp -= numArgsPushed - 1; // Remove all args but the receiver. auto obj = slotRawObject(recvrSlot); if (obj->IsImmutable()) { StoreToImmutableB(g, g->sp, g->ip); return; } const auto classIndex = methodRaw->specialIndex; if (numArgsPushed >= 2) { slotCopy(&obj->slots[classIndex], g->sp + 1); g->gc->GCWrite(obj, g->sp + 1); } else { SetNil(&obj->slots[classIndex]); } slotCopy(g->sp, recvrSlot); return; } case methReturnClassVar: { // Return a classvar. g->sp -= numArgsPushed - 1; // Remove all args but the receiver. slotCopy(g->sp, &g->classvars->slots[methodRaw->specialIndex]); return; } case methAssignClassVar: { // Assign classvar. g->sp -= numArgsPushed - 1; // Remove all args but the receiver. if (numArgsPushed >= 2) { slotCopy(&g->classvars->slots[methodRaw->specialIndex], g->sp + 1); g->gc->GCWrite(g->classvars, g->sp + 1); } else { SetNil(&g->classvars->slots[methodRaw->specialIndex]); } slotCopy(g->sp, recvrSlot); return; } case methRedirect: { // Send a different selector to this, e.g. this.subclassResponsibility. if (numArgsPushed < methodRaw->numargs) pushDefaultArgsIfNotEnoughSupplied(); if (numKeyArgsPushed > 0) applyKeywords(); selector = slotRawSymbol(&method->selectors); goto lookup_again; } case methRedirectSuper: { // Send a different selector to super, e.g. super.subclassResponsibility. if (numArgsPushed < methodRaw->numargs) pushDefaultArgsIfNotEnoughSupplied(); if (numKeyArgsPushed > 0) applyKeywords(); selector = slotRawSymbol(&method->selectors); classobj = slotRawSymbol(&slotRawClass(&method->ownerclass)->superclass)->u.classobj; goto lookup_again; } case methForwardInstVar: { // Forward to an object instance variable, e.g., ^foo.bar. if (numKeyArgsPushed > 0) applyKeywords(); else if (numArgsPushed < methodRaw->numargs) pushDefaultArgsIfNotEnoughSupplied(); selector = slotRawSymbol(&method->selectors); slotCopy(recvrSlot, &slotRawObject(recvrSlot)->slots[methodRaw->specialIndex]); classobj = classOfSlot(recvrSlot); goto lookup_again; } case methForwardClassVar: { // Forward to a class variable, e.g., ^Class.foo.bar. if (numKeyArgsPushed > 0) applyKeywords(); else if (numArgsPushed < methodRaw->numargs) pushDefaultArgsIfNotEnoughSupplied(); selector = slotRawSymbol(&method->selectors); slotCopy(recvrSlot, &g->classvars->slots[methodRaw->specialIndex]); classobj = classOfSlot(recvrSlot); goto lookup_again; } case methPrimitive: { // Some primitive, e.g., _SomeThing. if (numKeyArgsPushed > 0) doPrimitiveWithKeys(g, method, static_cast<int>(numArgsPushed), static_cast<int>(numKeyArgsPushed)); else doPrimitive(g, method, static_cast<int>(numArgsPushed)); return; } } } HOT void sendMessage(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed) { const GCSanityChecker gc_sanity_checker(g, "sendMessage"); auto recvrSlot = g->sp - numArgsPushed + 1; auto classobj = classOfSlot(recvrSlot); sendMessageImpl(g, selector, recvrSlot, classobj, numArgsPushed, numKeyArgsPushed); } HOT void sendSuperMessage(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed) { const GCSanityChecker gc_sanity_checker(g, "sendSuperMessage"); auto recvrSlot = g->sp - numArgsPushed + 1; auto classobj = slotRawSymbol(&slotRawClass(&g->method->ownerclass)->superclass)->u.classobj; sendMessageImpl(g, selector, recvrSlot, classobj, numArgsPushed, numKeyArgsPushed); } extern PyrClass* class_identdict; // An optimization for unique methods. // Returns false if it isn't a unique method. bool tryUniqueMethod(VMGlobals* g, PyrMethod* meth, PyrSlot* receiverSlot, PyrSlot* selectorSlot, long numArgsPushed, long numKeyArgsPushed) { if (slotRawClass(&meth->ownerclass) != class_object) return false; auto uniqueMethodSlot = &g->classvars->slots[cvxUniqueMethods]; if (!isKindOfSlot(uniqueMethodSlot, class_identdict)) return false; auto arraySlot = slotRawObject(uniqueMethodSlot)->slots + ivxIdentDict_array; if (!IsObj(arraySlot)) return false; auto array = slotRawObject(arraySlot); if (array->classptr != class_array) return false; auto i = arrayAtIdentityHashInPairs(array, receiverSlot); if (i < 0) return false; auto slot = array->slots + i; if (IsNil(slot)) return false; ++slot; if (!isKindOfSlot(slot, class_identdict)) return false; auto arraySlot2 = slotRawObject(slot)->slots + ivxIdentDict_array; if (!IsObj(arraySlot2)) return false; auto array2 = slotRawObject(arraySlot2); if (array2->classptr != class_array) return false; auto i2 = arrayAtIdentityHashInPairs(array2, selectorSlot); if (i2 < 0) return false; auto slot2 = array2->slots + i; if (IsNil(slot2)) return false; ++slot2; slotCopy(selectorSlot, receiverSlot); slotCopy(receiverSlot, slot2); blockValueWithKeys(g, static_cast<int>(numArgsPushed + 1), static_cast<int>(numKeyArgsPushed)); return true; } void doesNotUnderstand(VMGlobals* g, PyrSymbol* selector, long numArgsPushed, long numKeyArgsPushed) { const GCSanityChecker check(g, "doesNotUnderstand"); auto receiverSlot = g->sp - numArgsPushed + 1; auto classObject = classOfSlot(receiverSlot); // Push selector so it is after the receiver but before any arguments. SetSymbol(++g->sp, selector); if (numArgsPushed > 1) { // right rotate by one (skipping receiver) // moving args up and placing selector next to the receiver auto rargBegin = std::reverse_iterator<PyrSlot*>(g->sp + 1); auto rargEnd = std::reverse_iterator<PyrSlot*>(g->sp - numArgsPushed + 1); std::rotate(rargBegin, rargBegin + 1, rargEnd); } auto selectorSlot = g->sp - numArgsPushed + 1; const auto callIndex = slotRawInt(&classObject->classIndex) + s_doesNotUnderstand->u.index; auto method = gRowTable[callIndex]; if (tryUniqueMethod(g, method, receiverSlot, selectorSlot, numArgsPushed, numKeyArgsPushed)) return; executeMethod(g, method, numArgsPushed + 1, numKeyArgsPushed); } void kwArgMismatchErrorMethod(const char* argName, void* ptr) { auto meth = reinterpret_cast<PyrMethod*>(ptr); post("WARNING: keyword arg '%s' not found in call to %s:%s\n", argName, slotRawSymbol(&slotRawClass(&meth->ownerclass)->name)->name, slotRawSymbol(&meth->name)->name); } void kwArgMismatchErrorBlock(const char* argName, void*) { post("WARNING: keyword arg '%s' not found in call to function.\n", argName); } // This function puts the arguments into the passed in callFrame ready to be called. // It will also lookup arguments in the environment if one is passed in. void prepareArgsForExecute(VMGlobals* g, PyrBlock* block, PyrFrame* callFrame, long totalSuppliedArgs, long numKwArgsSupplied, bool isMethod, PyrObject* optionalEnvirLookup) { // There are some instances where the proto is a nullptr. // There is nothing this function can do in that case. if (!IsObj(&block->prototypeFrame)) return; PyrObject* proto = slotRawObject(&block->prototypeFrame); const PyrMethodRaw* methodRaw = METHRAW(block); const auto methNumActualArgs = methodRaw->posargs; const auto numNormalSuppliedArgs = totalSuppliedArgs - (numKwArgsSupplied * 2); const bool methHasVarArg = methodRaw->varargs > 0; const bool methHasKwArg = methodRaw->varargs > 1; const auto methNumNormArgs = methodRaw->numargs; const auto methNumVariables = methodRaw->numvars; const auto methArgNames = slotRawSymbolArray(&block->argNames)->symbols; PyrSlot* outCallFrameStack = callFrame->vars; PyrSlot* pushedArgs = g->sp - (totalSuppliedArgs - 1); PyrSlot* pushedKeywords = g->sp - (numKwArgsSupplied * 2 - 1); if (methNumActualArgs == 0) { std::copy(proto->slots, proto->slots + methNumVariables, outCallFrameStack); return; } // Optional arrays for variable arguments and keyword arguments. PyrObject* variableArgumentsArray = nullptr; PyrObject* keywordArgumentsArray = nullptr; int keywordArgumentSize = 0; const auto findKeywordArgIndex = [=](const PyrSymbol* argName) -> std::optional<uint32_t> { for (size_t namei = 0; namei < methNumNormArgs; ++namei) { const auto indexOffsetFromThis = namei + (isMethod ? 1 : 0); if (methArgNames[indexOffsetFromThis] == argName) return indexOffsetFromThis; } return std::nullopt; }; // Number that will actually be pushed to resulting call frame. const auto numNormalArgsAdded = std::min<uint32>(numNormalSuppliedArgs, methNumNormArgs); std::copy(pushedArgs, pushedArgs + numNormalArgsAdded, outCallFrameStack); if (numNormalSuppliedArgs > methNumNormArgs && methHasVarArg) { // Too many args. // Put extra in variable array if method supports it, otherwise drop them. const auto size = static_cast<int>(numNormalSuppliedArgs) - methNumNormArgs; variableArgumentsArray = newPyrArray(g->gc, size, 0, false); variableArgumentsArray->size = size; std::copy(pushedArgs + numNormalArgsAdded, pushedArgs + numNormalSuppliedArgs, variableArgumentsArray->slots); } else if (numNormalSuppliedArgs < methNumNormArgs) { // Too few args, push defaults. std::copy(proto->slots + numNormalArgsAdded, proto->slots + methNumNormArgs, outCallFrameStack + numNormalArgsAdded); // This is the only case where the optional environment is used to lookup arguments. if (optionalEnvirLookup) for (auto i = numNormalArgsAdded; i < methNumNormArgs; ++i) { PyrSlot keyslot; SetSymbol(&keyslot, methArgNames[i]); identDict_lookupNonNil(optionalEnvirLookup, &keyslot, calcHash(&keyslot), &outCallFrameStack[i]); } } // Deal with the keywords. for (size_t i = 0; i < numKwArgsSupplied * 2; i += 2) { PyrSymbol* argKeyword = slotRawSymbol(pushedKeywords + i); PyrSlot* argValue = pushedKeywords + i + 1; // If found in method. if (const auto argIndex = findKeywordArgIndex(argKeyword); argIndex.has_value()) { outCallFrameStack[*argIndex] = *argValue; // SC docs show that in the case of colliding args, the last one added should always be the result. if (*argIndex < numNormalArgsAdded) { // Already pushed, duplicate keyword found, update value, post warning. if (!isMethod) { post("Duplicate keyword '%s' at position %d found in function call\n", argKeyword->name, *argIndex); } else { auto* method = reinterpret_cast<PyrMethod*>(block); post("Duplicate keyword '%s' at position %d found in call to %s:%s\n", argKeyword->name, *argIndex, slotRawSymbol(&slotRawClass(&method->ownerclass)->name)->name, slotRawSymbol(&method->name)->name); } } } else if (methHasKwArg) { // Allocate if nullptr. keywordArgumentsArray = keywordArgumentsArray ? keywordArgumentsArray : newPyrArray(g->gc, static_cast<int>(numKwArgsSupplied) * 2, 0, false); // Add keyword and value to keywordArgumentsArray. SetSymbol(keywordArgumentsArray->slots + keywordArgumentSize, argKeyword); ++keywordArgumentSize; *(keywordArgumentsArray->slots + keywordArgumentSize) = *argValue; ++keywordArgumentSize; } else if (gKeywordError) { if (isMethod) kwArgMismatchErrorMethod(argKeyword->name, block); else kwArgMismatchErrorBlock(argKeyword->name, block); } } // Put var arg array or default on stack. if (methHasVarArg) { if (variableArgumentsArray) SetObject(outCallFrameStack + methNumNormArgs, variableArgumentsArray); else slotCopy(outCallFrameStack + methNumNormArgs, proto->slots + methNumNormArgs); } // Put var kwarg array or default on stack. if (methHasKwArg) { if (keywordArgumentsArray) { keywordArgumentsArray->size = keywordArgumentSize; SetObject(outCallFrameStack + methNumNormArgs + 1, keywordArgumentsArray); } else { slotCopy(outCallFrameStack + methNumNormArgs + 1, proto->slots + methNumNormArgs + 1); } } // Push default variable values to call_frame. std::copy(proto->slots + methNumActualArgs, proto->slots + methNumActualArgs + methNumVariables, outCallFrameStack + methNumActualArgs); } inline PyrFrame* createFrameForExecuteMethod(VMGlobals* g, PyrBlock* block) { const PyrMethodRaw* methraw = METHRAW(block); const PyrObject* proto = slotRawObject(&block->prototypeFrame); auto frame = reinterpret_cast<PyrFrame*>(g->gc->NewFrame(methraw->frameSize, 0, obj_slot, methraw->needsHeapContext)); frame->classptr = class_frame; frame->size = FRAMESIZE + proto->size; SetObject(&frame->method, block); SetObject(&frame->homeContext, frame); SetObject(&frame->context, frame); if (PyrFrame* caller = g->frame; caller != nullptr) { SetPtr(&caller->ip, g->ip); SetObject(&frame->caller, caller); } else { SetInt(&frame->caller, 0); } SetPtr(&frame->ip, nullptr); return frame; } HOT void executeMethod(VMGlobals* g, PyrBlock* meth, long totalNumArgsPushed, long numKwArgsPushed) { prepForTailCall(g); const GCSanityChecker gc_sanity_checker(g, "executeMethod"); auto callFrame = createFrameForExecuteMethod(g, meth); prepareArgsForExecute(g, meth, callFrame, totalNumArgsPushed, numKwArgsPushed, true); g->execMethod = numKwArgsPushed == 0 ? 20 : 10; g->method = (PyrMethod*)meth; g->ip = slotRawInt8Array(&meth->code)->b - 1; g->frame = callFrame; g->block = (PyrBlock*)meth; g->sp -= totalNumArgsPushed; slotCopy(&g->receiver, callFrame->vars); } void switchToThread(VMGlobals* g, PyrThread* newthread, int oldstate, int* numArgsPushed); HOT void returnFromBlock(VMGlobals* g) { const GCSanityChecker gc_sanity_checker(g, "returnFromBlock"); PyrFrame* curframe; PyrFrame* returnFrame; PyrFrame* homeContext; PyrBlock* block; PyrMethod* meth; PyrMethodRaw* methraw; // if (gTraceInterpreter) postfl("->returnFromBlock\n"); // printf("->returnFromBlock\n"); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); CallStackSanity(g, "returnFromBlock"); #endif curframe = g->frame; // again: returnFrame = slotRawFrame(&curframe->caller); if (returnFrame) { block = slotRawBlock(&curframe->method); g->frame = returnFrame; g->ip = (unsigned char*)slotRawPtr(&returnFrame->ip); g->block = slotRawBlock(&returnFrame->method); homeContext = slotRawFrame(&returnFrame->homeContext); meth = slotRawMethod(&homeContext->method); methraw = METHRAW(meth); slotCopy(&g->receiver, &homeContext->vars[0]); //?? g->method = meth; meth = slotRawMethod(&curframe->method); methraw = METHRAW(meth); if (!methraw->needsHeapContext) { g->gc->Free(curframe); } else { SetInt(&curframe->caller, 0); } } else { ////// this should never happen . error("return from Function at top of call stack.\n"); g->method = nullptr; g->block = nullptr; g->frame = nullptr; g->sp = g->gc->Stack()->slots - 1; longjmp(g->escapeInterpreter, 1); } // if (gTraceInterpreter) postfl("<-returnFromBlock\n"); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); CallStackSanity(g, "returnFromBlock"); #endif } HOT void returnFromMethod(VMGlobals* g) { GCSanityChecker gc_sanity_checker(g, "returnFromMethod"); PyrFrame *returnFrame, *curframe, *homeContext; PyrMethod* meth; PyrMethodRaw* methraw; curframe = g->frame; homeContext = slotRawFrame(&slotRawFrame(&curframe->context)->homeContext); if (homeContext == nullptr) { null_return: #if TAILCALLOPTIMIZE if (g->tailCall) return; // do nothing. #endif /* static bool once = true; if (once || gTraceInterpreter) { once = false; post("return all the way out. sd %d\n", g->sp - g->gc->Stack()->slots); postfl("%s:%s\n", slotRawClass(&g->method->ownerclass)->name.us->name, g->slotRawSymbol(&method->name)->name ); post("tailcall %d\n", g->tailCall); post("homeContext %p\n", homeContext); post("returnFrame %p\n", returnFrame); dumpObjectSlot(&homeContext->caller); DumpStack(g, g->sp); DumpBackTrace(g); } gTraceInterpreter = false; */ // if (IsNil(&homeContext->caller)) return; // do nothing. // return all the way out. PyrSlot* bottom = g->gc->Stack()->slots; slotCopy(bottom, g->sp); g->sp = bottom; // ??!! pop everybody g->method = nullptr; g->block = nullptr; g->frame = nullptr; longjmp(g->escapeInterpreter, 2); } else { returnFrame = slotRawFrame(&homeContext->caller); if (returnFrame == nullptr) goto null_return; // make sure returnFrame is a caller and find earliest stack frame { PyrFrame* tempFrame = curframe; while (tempFrame != returnFrame) { tempFrame = slotRawFrame(&tempFrame->caller); if (!tempFrame) { if (isKindOf((PyrObject*)g->thread, class_routine) && NotNil(&g->thread->parent)) { // not found, so yield to parent thread and continue searching. PyrSlot value; slotCopy(&value, g->sp); int numArgsPushed = 1; switchToThread(g, slotRawThread(&g->thread->parent), tSuspended, &numArgsPushed); // on the other side of the looking glass, put the yielded value on the stack as the result.. g->sp -= numArgsPushed - 1; slotCopy(g->sp, &value); curframe = tempFrame = g->frame; } else { slotCopy(&g->sp[2], &g->sp[0]); slotCopy(g->sp, &g->receiver); g->sp++; SetObject(g->sp, g->method); g->sp++; sendMessage(g, getsym("outOfContextReturn"), 3, 0); return; } } } } { PyrFrame* tempFrame = curframe; while (tempFrame != returnFrame) { meth = slotRawMethod(&tempFrame->method); methraw = METHRAW(meth); PyrFrame* nextFrame = slotRawFrame(&tempFrame->caller); if (!methraw->needsHeapContext) { SetInt(&tempFrame->caller, 0); } else { if (tempFrame != homeContext) SetInt(&tempFrame->caller, 0); } tempFrame = nextFrame; } } // return to it g->ip = (unsigned char*)slotRawPtr(&returnFrame->ip); g->frame = returnFrame; g->block = slotRawBlock(&returnFrame->method); homeContext = slotRawFrame(&returnFrame->homeContext); meth = slotRawMethod(&homeContext->method); methraw = METHRAW(meth); #if DEBUGMETHODS if (gTraceInterpreter) { postfl("%s:%s <- %s:%s\n", slotRawSymbol(&slotRawClass(&meth->ownerclass)->name)->name, slotRawSymbol(&meth->name)->name, slotRawSymbol(&slotRawClass(&g->method->ownerclass)->name)->name, slotRawSymbol(&g->method->name)->name); } #endif g->method = meth; slotCopy(&g->receiver, &homeContext->vars[0]); } } int keywordFixStack(VMGlobals* g, PyrMethod* meth, PyrMethodRaw* methraw, long allArgsPushed, long numKeyArgsPushed) { PyrSlot *pslot, *qslot; long i, j, m, diff, numArgsPushed, numArgsNeeded; if (numKeyArgsPushed) { // evacuate keyword args to separate area pslot = temporaryKeywordStack + (numKeyArgsPushed << 1); qslot = g->sp + 1; for (m = 0; m < numKeyArgsPushed; ++m) { *--pslot = *--qslot; *--pslot = *--qslot; } } PyrSlot* vars = g->sp - allArgsPushed + 1; numArgsPushed = allArgsPushed - (numKeyArgsPushed << 1); numArgsNeeded = methraw->numargs; diff = numArgsNeeded - numArgsPushed; if (diff > 0) { // not enough args pslot = vars + numArgsPushed - 1; qslot = slotRawObject(&meth->prototypeFrame)->slots + numArgsPushed - 1; for (m = 0; m < diff; ++m) slotCopy(++pslot, ++qslot); numArgsPushed = numArgsNeeded; } // do keyword lookup: if (numKeyArgsPushed && methraw->posargs) { PyrSymbol** name0 = slotRawSymbolArray(&meth->argNames)->symbols + 1; PyrSlot* key = temporaryKeywordStack; for (i = 0; i < numKeyArgsPushed; ++i, key += 2) { PyrSymbol** name = name0; for (j = 1; j < methraw->posargs; ++j, ++name) { if (*name == slotRawSymbol(key)) { slotCopy(&vars[j], &key[1]); goto found; } } if (gKeywordError) kwArgMismatchErrorMethod(slotRawSymbol(key)->name, meth); found:; } } g->sp += numArgsPushed - allArgsPushed; return static_cast<int>(numArgsPushed); }
28,564
C++
.cpp
653
35.471669
120
0.642885
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,839
ByteCodeArray.cpp
supercollider_supercollider/lang/LangSource/ByteCodeArray.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> #include "SCBase.h" #include "InitAlloc.h" #include "ByteCodeArray.h" #include "Opcodes.h" ByteCodes gCompilingByteCodes; long totalByteCodes = 0; void initByteCodes() { if (gCompilingByteCodes) { freeByteCodes(gCompilingByteCodes); gCompilingByteCodes = nullptr; } } int compileOpcode(long opcode, long operand1) { int retc; if (operand1 <= 15) { compileByte((opcode << 4) | operand1); retc = 1; } else { compileByte(opcode); compileByte(operand1); if (opcode == opSendMsg || opcode == opSendSpecialMsg || opcode == opSendSuper) { // these expect numKeyArgsPushed to be passed. compileByte(0); } retc = 2; } return retc; } void compileJump(long opcode, long jumplen) { compileByte((opSpecialOpcode << 4) | opcode); compileByte((jumplen >> 8) & 0xFF); compileByte(jumplen & 0xFF); } void compileByte(long byte) { if (gCompilingByteCodes == nullptr) { gCompilingByteCodes = allocByteCodes(); } if ((gCompilingByteCodes->ptr - gCompilingByteCodes->bytes) >= gCompilingByteCodes->size) { reallocByteCodes(gCompilingByteCodes); } totalByteCodes++; *gCompilingByteCodes->ptr++ = byte; } int compileNumber(unsigned long value) { compileByte((value >> 24) & 0xFF); compileByte((value >> 16) & 0xFF); compileByte((value >> 8) & 0xFF); compileByte(value & 0xFF); return 4; } int compileNumber24(unsigned long value) { compileByte((value >> 16) & 0xFF); compileByte((value >> 8) & 0xFF); compileByte(value & 0xFF); return 4; } void compileAndFreeByteCodes(ByteCodes byteCodes) { compileByteCodes(byteCodes); freeByteCodes(byteCodes); } void copyByteCodes(Byte* dest, ByteCodes byteCodes) { memcpy(dest, byteCodes->bytes, byteCodeLength(byteCodes)); } ByteCodes getByteCodes() { ByteCodes curByteCodes; curByteCodes = gCompilingByteCodes; gCompilingByteCodes = nullptr; return curByteCodes; } ByteCodes saveByteCodeArray() { ByteCodes curByteCodes; curByteCodes = gCompilingByteCodes; gCompilingByteCodes = nullptr; return curByteCodes; } void restoreByteCodeArray(ByteCodes byteCodes) { gCompilingByteCodes = byteCodes; } size_t byteCodeLength(ByteCodes byteCodes) { if (!byteCodes) return 0; return (byteCodes->ptr - byteCodes->bytes); } /*********************************************************************** * * Internal routines. * ***********************************************************************/ void compileByteCodes(ByteCodes byteCodes) { Byte* ptr; int i; if (byteCodes == nullptr) return; // postfl("[%d]\n", byteCodes->ptr - byteCodes->bytes); for (i = 0, ptr = byteCodes->bytes; ptr < byteCodes->ptr; ptr++, ++i) { compileByte(*ptr); // postfl("%02X ", *ptr); // if ((i & 15) == 15) postfl("\n"); } // postfl("\n\n"); } ByteCodes allocByteCodes() { ByteCodes newByteCodes; // pyrmalloc: I think that all bytecodes are copied to objects // lifetime: kill after compile newByteCodes = (ByteCodes)pyr_pool_compile->Alloc(sizeof(ByteCodeArray)); MEMFAIL(newByteCodes); newByteCodes->bytes = (Byte*)pyr_pool_compile->Alloc(BYTE_CODE_CHUNK_SIZE); MEMFAIL(newByteCodes->bytes); newByteCodes->ptr = newByteCodes->bytes; newByteCodes->size = BYTE_CODE_CHUNK_SIZE; // postfl("allocByteCodes %0X\n", newByteCodes); return newByteCodes; } void reallocByteCodes(ByteCodes byteCodes) { Byte* newBytes; if (byteCodes->size != (byteCodes->ptr - byteCodes->bytes)) { error("reallocByteCodes called with size != byteCode len"); } size_t newLen = byteCodes->size << 1; // pyrmalloc: I think that all bytecodes are copied to objects // lifetime: kill after compile newBytes = (Byte*)pyr_pool_compile->Alloc(newLen); MEMFAIL(newBytes); memcpy(newBytes, byteCodes->bytes, byteCodes->size); pyr_pool_compile->Free(byteCodes->bytes); byteCodes->bytes = newBytes; byteCodes->ptr = newBytes + byteCodes->size; byteCodes->size = newLen; } void freeByteCodes(ByteCodes byteCodes) { // postfl("freeByteCodes %0X\n", byteCodes); if (byteCodes != nullptr) { pyr_pool_compile->Free(byteCodes->bytes); pyr_pool_compile->Free(byteCodes); } }
5,327
C++
.cpp
151
30.602649
114
0.674966
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,841
VMGlobals.cpp
supercollider_supercollider/lang/LangSource/VMGlobals.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "VMGlobals.h" VMGlobals::VMGlobals(): allocPool(nullptr), process(nullptr), gc(nullptr), classvars(nullptr), canCallOS(false), thread(nullptr), method(nullptr), block(nullptr), frame(nullptr), primitiveMethod(nullptr), ip(nullptr), sp(nullptr), numpop(0), primitiveIndex(0), execMethod(0) { SetNil(&receiver); SetNil(&result); }
1,282
C++
.cpp
36
31
81
0.727419
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
29,842
PyrParseNode.cpp
supercollider_supercollider/lang/LangSource/PyrParseNode.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SCBase.h" #include "PyrParseNode.h" #include "PyrLexer.h" #include "PyrKernel.h" #include "PyrListPrim.h" #include "PyrSymbolTable.h" #include "Opcodes.h" #include "PyrKernelProto.h" #include "PyrObjectProto.h" #include "GC.h" #include <new> #include <string> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include "InitAlloc.h" #include "PredefinedSymbols.h" #include "SimpleStack.h" #include "PyrPrimitive.h" #include "SC_Win32Utils.h" #include "SC_LanguageConfig.hpp" #include "SC_Codecvt.hpp" namespace fs = std::filesystem; AdvancingAllocPool gParseNodePool; PyrSymbol* gSpecialUnarySelectors[opNumUnarySelectors]; PyrSymbol* gSpecialBinarySelectors[opNumBinarySelectors]; PyrSymbol* gSpecialSelectors[opmNumSpecialSelectors]; PyrSymbol* gSpecialClasses[op_NumSpecialClasses]; PyrSlot gSpecialValues[svNumSpecialValues]; PyrParseNode* gRootParseNode; intptr_t gParserResult; int conjureConstantIndex(PyrParseNode* node, PyrBlock* func, PyrSlot* slot); void compilePushConstant(PyrParseNode* node, PyrSlot* slot); PyrClass* gCurrentClass = nullptr; PyrClass* gCurrentMetaClass = nullptr; PyrClass* gCompilingClass = nullptr; PyrMethod* gCompilingMethod = nullptr; PyrBlock* gCompilingBlock = nullptr; PyrBlock* gPartiallyAppliedFunction = nullptr; bool gIsTailCodeBranch = false; bool gTailIsMethodReturn = false; int gFunctionHighestExternalRef = 1; bool gFunctionCantBeClosed = true; #if TAILCALLOPTIMIZE bool gGenerateTailCallByteCodes = true; #else bool gGenerateTailCallByteCodes = false; #endif long gInliningLevel; int compileErrors = 0; int numOverwrites = 0; std::string overwriteMsg; extern bool compilingCmdLine; extern int errLineOffset, errCharPosOffset; const char* nodename[] = { "ClassNode", "ClassExtNode", "MethodNode", "BlockNode", "SlotNode", /* variable declarations */ "VarListNode", "VarDefNode", "DynDictNode", "DynListNode", "LitListNode", "LitDictNode", "StaticVarListNode", "InstVarListNode", "PoolVarListNode", "ArgListNode", "SlotDefNode", /* selectors */ "LiteralNode", /* code */ "PushLitNode", "PushNameNode", "PushKeyArgNode", "CallNode", "BinopCallNode", "DropNode", "AssignNode", "MultiAssignNode", "MultiAssignVarListNode", "SetterNode", "CurryArgNode", "ReturnNode", "BlockReturnNode" }; void compileTail() { if (gGenerateTailCallByteCodes && gIsTailCodeBranch) { // if (gCompilingClass && gCompilingMethod) post("tail call %s:%s ismethod %d\n", // slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, // gTailIsMethodReturn); if (gTailIsMethodReturn) compileByte(255); else compileByte(176); } } PyrGC* compileGC(); PyrGC* compileGC() { return gCompilingVMGlobals ? gCompilingVMGlobals->gc : nullptr; } void initParser() { compileErrors = 0; numOverwrites = 0; overwriteMsg.clear(); } void finiParser() {} void initParseNodes() {} void initParserPool() { // postfl("initPool gParseNodePool pyr_pool_compile\n"); gParseNodePool.Init(pyr_pool_compile, 32000, 32000, 2000); } void freeParserPool() { // postfl("freePool gParseNodePool pyr_pool_compile\n"); gParseNodePool.FreeAll(); } PyrParseNode::PyrParseNode(int inClassNo) { mClassno = inClassNo; mNext = nullptr; mTail = this; mCharno = ::charno; mLineno = ::lineno; mParens = 0; } void compileNodeList(PyrParseNode* node, bool onTailBranch) { PyrSlot dummy; // postfl("->compileNodeList\n"); for (; node; node = node->mNext) { // postfl("-->compileNodeList %p\n", node); COMPILENODE(node, &dummy, onTailBranch); // postfl("<--compileNodeList %p\n", node); } // postfl("<-compileNodeList\n"); } void nodePostErrorLine(PyrParseNode* node) { postErrorLine(node->mLineno, linestarts[node->mLineno], node->mCharno); } PyrPushNameNode* newPyrPushNameNode(PyrSlotNode* slotNode) { slotNode->mClassno = pn_PushNameNode; return (PyrPushNameNode*)slotNode; } void compilePushVar(PyrParseNode* node, PyrSymbol* varName) { int level, index, vindex, varType; PyrBlock* tempfunc; PyrClass* classobj; // postfl("compilePushVar\n"); classobj = gCompilingClass; if (varName->name[0] >= 'A' && varName->name[0] <= 'Z') { if (compilingCmdLine && varName->u.classobj == nullptr) { error("Class not defined.\n"); nodePostErrorLine(node); compileErrors++; } else { if (findSpecialClassName(varName, &index)) { compileOpcode(opExtended, opPushSpecialValue); // special op for pushing a class compileByte(index); } else { PyrSlot slot; SetSymbol(&slot, varName); index = conjureLiteralSlotIndex(node, gCompilingBlock, &slot); compileOpcode(opExtended, opExtended); // special op for pushing a class compileByte(index); } } } else if (varName == s_this || varName == s_super) { gFunctionCantBeClosed = true; compileOpcode(opPushSpecialValue, opsvSelf); } else if (varName == s_true) { compileOpcode(opPushSpecialValue, opsvTrue); } else if (varName == s_false) { compileOpcode(opPushSpecialValue, opsvFalse); } else if (varName == s_nil) { compileOpcode(opPushSpecialValue, opsvNil); } else if (findVarName(gCompilingBlock, &classobj, varName, &varType, &level, &index, &tempfunc)) { switch (varType) { case varInst: compileOpcode(opPushInstVar, index); break; case varClass: { index += slotRawInt(&classobj->classVarIndex); if (index < 4096) { compileByte((opPushClassVar << 4) | ((index >> 8) & 15)); compileByte(index & 255); } else { compileByte(opPushClassVar); compileByte((index >> 8) & 255); compileByte(index & 255); } } break; case varConst: { PyrSlot* slot = slotRawObject(&classobj->constValues)->slots + index; compilePushConstant(node, slot); } break; case varTemp: vindex = index; if (level == 0) { compileOpcode(opPushTempZeroVar, vindex); } else if (level < 8) { compileOpcode(opPushTempVar, level); compileByte(vindex); } else { compileByte(opPushTempVar); compileByte(level); compileByte(vindex); } break; case varPseudo: compileOpcode(opExtended, opSpecialOpcode); compileByte(index); break; } } else { error("Variable '%s' not defined.\n", varName->name); nodePostErrorLine(node); compileErrors++; // Debugger(); } } PyrCurryArgNode* newPyrCurryArgNode() { PyrCurryArgNode* node = ALLOCNODE(PyrCurryArgNode); return node; } void PyrCurryArgNode::compile(PyrSlot* result) { if (gPartiallyAppliedFunction) { compileOpcode(opPushTempZeroVar, mArgNum); } else { error("found _ argument outside of a call.\n"); nodePostErrorLine((PyrParseNode*)this); compileErrors++; } } PyrSlotNode* newPyrSlotNode(PyrSlot* slot) { PyrSlotNode* node = ALLOCNODE(PyrSlotNode); node->mSlot = *slot; return node; } void PyrSlotNode::compile(PyrSlot* result) { if (mClassno == pn_LiteralNode) compileLiteral(result); else if (mClassno == pn_PushLitNode) compilePushLit(result); else if (mClassno == pn_PushNameNode) compilePushVar((PyrParseNode*)this, slotRawSymbol(&mSlot)); else { error("compilePyrSlotNode: shouldn't get here.\n"); dumpObjectSlot(&mSlot); nodePostErrorLine((PyrParseNode*)this); compileErrors++; // Debugger(); } } PyrClassExtNode* newPyrClassExtNode(PyrSlotNode* className, PyrMethodNode* methods) { PyrClassExtNode* node = ALLOCNODE(PyrClassExtNode); node->mClassName = className; node->mMethods = methods; return node; } void PyrClassExtNode::compile(PyrSlot* result) { PyrClass* classobj = slotRawSymbol(&mClassName->mSlot)->u.classobj; if (!classobj) { const fs::path relpath = relativeToCompileDir(fs::path(gCompilingFileSym->name)); error("Class extension for nonexistent class '%s'\n In file:'%s'\n", slotRawSymbol(&mClassName->mSlot)->name, SC_Codecvt::path_to_utf8_str(relpath).c_str()); return; } gCurrentClass = classobj; gCurrentMetaClass = classobj->classptr; compileExtNodeMethods(this); } void compileExtNodeMethods(PyrClassExtNode* node) { PyrMethodNode* method; method = node->mMethods; for (; method; method = (PyrMethodNode*)method->mNext) { PyrSlot dummy; // post("compile ext %s:%s\n", method->mExtension = true; compilePyrMethodNode(method, &dummy); } gCompilingMethod = nullptr; gCompilingBlock = nullptr; gPartiallyAppliedFunction = nullptr; gInliningLevel = 0; } PyrClassNode* newPyrClassNode(PyrSlotNode* className, PyrSlotNode* superClassName, PyrVarListNode* varlists, PyrMethodNode* methods, PyrSlotNode* indexType) { PyrClassNode* node = ALLOCNODE(PyrClassNode); node->mClassName = className; node->mIndexType = indexType; node->mSuperClassName = superClassName; node->mVarlists = varlists; node->mMethods = methods; node->mVarTally[varInst] = 0; node->mVarTally[varClass] = 0; node->mVarTally[varTemp] = 0; node->mVarTally[varConst] = 0; // node->mVarTally[varPool] = 0; return node; } bool compareVarDefs(PyrClassNode* node, PyrClass* classobj) { int numinstvars, numclassvars; int i, xinst, xclass; PyrVarListNode* varlist; PyrVarDefNode* vardef; PyrParseNode* errnode; PyrSymbol** varNames; bool isIntrinsic; isIntrinsic = slotRawInt(&classobj->classFlags) & classIsIntrinsic; numinstvars = numInstVars(classobj); numclassvars = numClassVars(classobj); if (numinstvars == node->mVarTally[varInst] + node->mNumSuperInstVars && numclassvars == node->mVarTally[varClass]) { xclass = 0; xinst = node->mNumSuperInstVars; varlist = node->mVarlists; for (; varlist; varlist = (PyrVarListNode*)varlist->mNext) { int type = varlist->mFlags; if (type == varInst) { vardef = varlist->mVarDefs; varNames = slotRawSymbolArray(&classobj->instVarNames)->symbols; for (i = 0; vardef; vardef = (PyrVarDefNode*)vardef->mNext, xinst++, ++i) { if (slotRawSymbol(&vardef->mVarName->mSlot) != varNames[xinst]) { errnode = (PyrParseNode*)vardef; // post("A %s %d %d %d\n", vardef->mVarName->slotRawSymbol(&mSlot)->name, // vardef->mVarName->slotRawSymbol(&mSlot), varNames[xinst].us, xinst); // post("A %s %s %d\n", vardef->mVarName->slotRawSymbol(&mSlot)->name, // varNames[xinst].us->name, xinst); goto differExit; } } } else if (type == varClass) { vardef = varlist->mVarDefs; varNames = slotRawSymbolArray(&classobj->classVarNames)->symbols; for (i = 0; vardef && xclass < numclassvars; vardef = (PyrVarDefNode*)vardef->mNext, xclass++, ++i) { if (slotRawSymbol(&vardef->mVarName->mSlot) != varNames[xclass]) { errnode = (PyrParseNode*)vardef; // post("B %d %d %d\n", vardef->mVarName->slotRawSymbol(&mSlot), varNames[xclass].us, xclass); goto differExit; } } } } } else { // post("C %d %d %d %d %d\n", numinstvars, node->mVarTally[varInst], node->mNumSuperInstVars, // numclassvars, node->mVarTally[varClass]); errnode = (node->mVarlists ? (PyrParseNode*)node->mVarlists : (PyrParseNode*)node->mClassName); goto differExit; } return false; differExit: if (isIntrinsic) { error("You may not change variable definitions of intrinsic classes.\n"); nodePostErrorLine(errnode); compileErrors++; } return true; } void countClassVarDefs(PyrClassNode* node, int* numClassMethods, int* numInstMethods) { PyrVarListNode* varlist; PyrVarDefNode* vardef; //*numClassMethods = 0; //*numInstMethods = 0; node->mVarTally[varInst] = 0; node->mVarTally[varClass] = 0; node->mVarTally[varTemp] = 0; node->mVarTally[varConst] = 0; // count number of variables of each type varlist = node->mVarlists; for (; varlist; varlist = (PyrVarListNode*)varlist->mNext) { int type = varlist->mFlags; vardef = varlist->mVarDefs; for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { node->mVarTally[type]++; if (type == varClass) { if (vardef->mFlags & rwReadOnly) { *numClassMethods = *numClassMethods + 1; } if (vardef->mFlags & rwWriteOnly) { *numClassMethods = *numClassMethods + 1; } } else if (type == varInst) { if (vardef->mFlags & rwReadOnly) { *numInstMethods = *numInstMethods + 1; } if (vardef->mFlags & rwWriteOnly) { *numInstMethods = *numInstMethods + 1; } } } } } void countNodeMethods(PyrClassNode* node, int* numClassMethods, int* numInstMethods) { // count methods PyrMethodNode* method; //*numClassMethods = 0; //*numInstMethods = 0; method = node->mMethods; for (; method; method = (PyrMethodNode*)method->mNext) { if (method->mIsClassMethod) *numClassMethods = *numClassMethods + 1; else *numInstMethods = *numInstMethods + 1; } } void compileNodeMethods(PyrClassNode* node) { PyrMethodNode* method; method = node->mMethods; for (; method; method = (PyrMethodNode*)method->mNext) { PyrSlot dummy; method->mExtension = false; compilePyrMethodNode(method, &dummy); } gCompilingMethod = nullptr; gCompilingBlock = nullptr; gPartiallyAppliedFunction = nullptr; gInliningLevel = 0; } PyrClass* getNodeSuperclass(PyrClassNode* node) { PyrClass* superclassobj = nullptr; // postfl("getNodeSuperclass node %d\n", node); // postfl("getNodeSuperclass node->mSuperClassName %d\n", node->mSuperClassName); // postfl("getNodeSuperclass node->mSuperClassName->mSlot.utag %d\n", // node->mSuperClassName->mSlot.utag); if (node->mSuperClassName && IsSym(&node->mSuperClassName->mSlot)) { superclassobj = slotRawSymbol(&node->mSuperClassName->mSlot)->u.classobj; if (superclassobj == nullptr) { error("Cannot find superclass '%s' for class '%s'\n", slotSymString(&node->mSuperClassName->mSlot), slotSymString(&node->mClassName->mSlot)); nodePostErrorLine((PyrParseNode*)node->mSuperClassName); superclassobj = (PyrClass*)-1; compileErrors++; } } else { if (slotRawSymbol(&node->mClassName->mSlot) != s_object) { superclassobj = class_object; } // else this is object and there is no superclass } return superclassobj; } void fillClassPrototypes(PyrClassNode* node, PyrClass* classobj, PyrClass* superclassobj) { PyrVarListNode* varlist; PyrVarDefNode* vardef; PyrSlot *islot, *cslot, *kslot; PyrSymbol **inameslot, **cnameslot, **knameslot; PyrClass* metaclassobj; PyrMethod* method; PyrMethodRaw* methraw; int instVarIndex, classVarIndex; // copy superclass's prototype to here if (superclassobj && NotNil(&superclassobj->iprototype) && slotRawObject(&superclassobj->iprototype)->size) { memcpy(slotRawObject(&classobj->iprototype)->slots, slotRawObject(&superclassobj->iprototype)->slots, sizeof(PyrSlot) * slotRawObject(&superclassobj->iprototype)->size); // slotRawObject(&classobj->iprototype)->size = slotRawObject(&superclassobj->iprototype)->size; slotRawObject(&classobj->iprototype)->size = node->mNumSuperInstVars; memcpy(slotRawSymbolArray(&classobj->instVarNames)->symbols, slotRawSymbolArray(&superclassobj->instVarNames)->symbols, sizeof(PyrSymbol*) * slotRawObject(&superclassobj->instVarNames)->size); // slotRawObject(&classobj->instVarNames)->size = slotRawObject(&superclassobj->iprototype)->size; slotRawObject(&classobj->instVarNames)->size = node->mNumSuperInstVars; } // fill the class' own part of prototypes metaclassobj = classobj->classptr; varlist = node->mVarlists; if (NotNil(&classobj->iprototype)) { islot = slotRawObject(&classobj->iprototype)->slots + node->mNumSuperInstVars; } if (NotNil(&classobj->cprototype)) { cslot = slotRawObject(&classobj->cprototype)->slots; } if (NotNil(&classobj->constValues)) { kslot = slotRawObject(&classobj->constValues)->slots; } if (NotNil(&classobj->instVarNames)) { inameslot = slotRawSymbolArray(&classobj->instVarNames)->symbols + node->mNumSuperInstVars; } if (NotNil(&classobj->classVarNames)) { cnameslot = slotRawSymbolArray(&classobj->classVarNames)->symbols; } if (NotNil(&classobj->constNames)) { knameslot = slotRawSymbolArray(&classobj->constNames)->symbols; } instVarIndex = node->mNumSuperInstVars; classVarIndex = 0; for (; varlist; varlist = (PyrVarListNode*)varlist->mNext) { int type = varlist->mFlags; switch (type) { case varInst: vardef = varlist->mVarDefs; for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot litslot; compilePyrLiteralNode((PyrLiteralNode*)vardef->mDefVal, &litslot); *islot++ = litslot; slotRawObject(&classobj->iprototype)->size++; *inameslot++ = slotRawSymbol(&vardef->mVarName->mSlot); slotRawSymbolArray(&classobj->instVarNames)->size++; if (vardef->mFlags & rwReadOnly) { // create getter method method = newPyrMethod(); methraw = METHRAW(method); methraw->unused1 = 0; methraw->unused2 = 0; methraw->numargs = 1; methraw->numvars = 0; methraw->posargs = 1; methraw->varargs = 0; methraw->numtemps = 1; methraw->popSize = 0; SetNil(&method->contextDef); SetNil(&method->varNames); SetObject(&method->ownerclass, classobj); if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[vardef->mVarName->mLineno] + errCharPosOffset); slotCopy(&method->name, &vardef->mVarName->mSlot); methraw->methType = methReturnInstVar; methraw->specialIndex = instVarIndex; addMethod(classobj, method); } if (vardef->mFlags & rwWriteOnly) { char setterName[256]; PyrSymbol* setterSym; sprintf(setterName, "%s_", slotRawSymbol(&vardef->mVarName->mSlot)->name); // underscore = strcpy(setterName, slotRawSymbol(&vardef->mVarName->mSlot)->name); // underscore[0] = '_'; // underscore[1] = 0; setterSym = getsym(setterName); // create setter method method = newPyrMethod(); methraw = METHRAW(method); methraw->unused1 = 0; methraw->unused2 = 0; methraw->numargs = 2; methraw->numvars = 0; methraw->posargs = 2; methraw->varargs = 0; methraw->numtemps = 2; methraw->popSize = 1; SetNil(&method->contextDef); SetNil(&method->varNames); SetObject(&method->ownerclass, classobj); SetSymbol(&method->name, setterSym); if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[vardef->mVarName->mLineno] + errCharPosOffset); methraw->methType = methAssignInstVar; methraw->specialIndex = instVarIndex; addMethod(classobj, method); } instVarIndex++; } break; case varClass: vardef = varlist->mVarDefs; for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot litslot; compilePyrLiteralNode((PyrLiteralNode*)vardef->mDefVal, &litslot); *cslot++ = litslot; slotRawObject(&classobj->cprototype)->size++; *cnameslot++ = slotRawSymbol(&vardef->mVarName->mSlot); slotRawSymbolArray(&classobj->classVarNames)->size++; if (vardef->mFlags & rwReadOnly) { // create getter method method = newPyrMethod(); methraw = METHRAW(method); methraw->unused1 = 0; methraw->unused2 = 0; methraw->numargs = 1; methraw->numvars = 0; methraw->posargs = 1; methraw->varargs = 0; methraw->numtemps = 1; methraw->popSize = 0; SetNil(&method->contextDef); SetNil(&method->varNames); SetObject(&method->ownerclass, metaclassobj); slotCopy(&method->name, &vardef->mVarName->mSlot); SetSymbol(&method->selectors, slotRawSymbol(&classobj->name)); if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[vardef->mVarName->mLineno] + errCharPosOffset); methraw->methType = methReturnClassVar; methraw->specialIndex = classVarIndex + slotRawInt(&classobj->classVarIndex); addMethod(metaclassobj, method); } if (vardef->mFlags & rwWriteOnly) { char setterName[256]; PyrSymbol* setterSym; sprintf(setterName, "%s_", slotRawSymbol(&vardef->mVarName->mSlot)->name); // underscore = strcpy(setterName, slotRawSymbol(&vardef->mVarName->mSlot)->name); // underscore[0] = '_'; // underscore[1] = 0; setterSym = getsym(setterName); // create setter method method = newPyrMethod(); methraw = METHRAW(method); methraw->numargs = 2; methraw->numvars = 0; methraw->posargs = 2; methraw->varargs = 0; methraw->numtemps = 2; methraw->popSize = 1; SetNil(&method->contextDef); SetNil(&method->varNames); SetObject(&method->ownerclass, metaclassobj); SetSymbol(&method->name, setterSym); SetSymbol(&method->selectors, slotRawSymbol(&classobj->name)); if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[vardef->mVarName->mLineno] + errCharPosOffset); methraw->methType = methAssignClassVar; methraw->specialIndex = classVarIndex + slotRawInt(&classobj->classVarIndex); addMethod(metaclassobj, method); } classVarIndex++; } break; case varConst: vardef = varlist->mVarDefs; for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot litslot; compilePyrLiteralNode((PyrLiteralNode*)vardef->mDefVal, &litslot); *kslot++ = litslot; slotRawObject(&classobj->constValues)->size++; *knameslot++ = slotRawSymbol(&vardef->mVarName->mSlot); slotRawSymbolArray(&classobj->constNames)->size++; if (vardef->mFlags & rwReadOnly) { // create getter method method = newPyrMethod(); methraw = METHRAW(method); methraw->unused1 = 0; methraw->unused2 = 0; methraw->numargs = 1; methraw->numvars = 0; methraw->posargs = 1; methraw->varargs = 0; methraw->numtemps = 1; methraw->popSize = 0; SetNil(&method->contextDef); SetNil(&method->varNames); SetObject(&method->ownerclass, metaclassobj); slotCopy(&method->name, &vardef->mVarName->mSlot); if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[vardef->mVarName->mLineno] + errCharPosOffset); methraw->methType = methReturnLiteral; slotCopy(&method->selectors, &litslot); addMethod(metaclassobj, method); } } break; } } } int getIndexType(PyrClassNode* classnode) { PyrSlotNode* node; int res; node = classnode->mIndexType; if (node == nullptr) res = obj_notindexed; else { char* name; name = slotRawSymbol(&node->mSlot)->name; if (strcmp(name, "slot") == 0) res = obj_slot; else if (strcmp(name, "double") == 0) res = obj_double; else if (strcmp(name, "float") == 0) res = obj_float; else if (strcmp(name, "int32") == 0) res = obj_int32; else if (strcmp(name, "int16") == 0) res = obj_int16; else if (strcmp(name, "int8") == 0) res = obj_int8; else if (strcmp(name, "char") == 0) res = obj_char; else if (strcmp(name, "symbol") == 0) res = obj_symbol; else { error("Illegal indexed type. Must be one of:\n" " slot, double, float, int8, int16, int32, char\n"); res = obj_slot; compileErrors++; } } return res; } void PyrClassNode::compile(PyrSlot* result) { PyrClass *classobj, *superclassobj, *metaclassobj; int numClassMethods, numInstMethods; bool isIntrinsic; bool varsDiffer, superclassesDiffer, indexTypesDiffer; bool shouldRecompileSubclasses = false; int indexType; // find num instvars in superclass // postfl("class '%s'\n", slotRawSymbol(&mClassName->mSlot)->name); superclassobj = getNodeSuperclass(this); indexType = getIndexType(this); // postfl("%s %d\n", slotRawSymbol(&mClassName->mSlot)->name, indexType); if ((size_t)superclassobj == -1) { // redundant error message removed: // error("Can't find superclass of '%s'\n", slotRawSymbol(&mClassName->mSlot)->name); // nodePostErrorLine(node); return; // can't find superclass } mNumSuperInstVars = numSuperInstVars(superclassobj); numClassMethods = 0; numInstMethods = 0; countClassVarDefs(this, &numClassMethods, &numInstMethods); // postfl("accessor methods %d %d\n", numClassMethods, numInstMethods); countNodeMethods(this, &numClassMethods, &numInstMethods); // postfl("total methods %d %d\n", numClassMethods, numInstMethods); // get or make a class object // see if it already exists classobj = slotRawSymbol(&mClassName->mSlot)->u.classobj; if (classobj) { // deal with intrinsic classes or other classes being recompiled here. // recompile of subclasses not necessary if inst and class vars are // unchanged. metaclassobj = (PyrClass*)classobj->classptr; isIntrinsic = slotRawInt(&classobj->classFlags) & classIsIntrinsic; varsDiffer = compareVarDefs(this, classobj); if (varsDiffer) { if (isIntrinsic) { // error("Class '%s' declaration doesn't match intrinsic definition.\n", // slotRawSymbol(&mClassName->mSlot)->name); return; } else { shouldRecompileSubclasses = true; } } superclassesDiffer = superclassobj != slotRawSymbol(&classobj->superclass)->u.classobj; indexTypesDiffer = indexType != slotRawInt(&classobj->instanceFormat); // postfl("%d %d %d\n", indexType, slotRawInt(&classobj->instanceFormat)); // if (varsDiffer || superclassesDiffer || indexTypesDiffer) { if (varsDiffer || superclassesDiffer || indexTypesDiffer) { if (isIntrinsic) { if (superclassesDiffer) { error("Superclass of '%s' does not match intrinsic definition.\n", slotRawSymbol(&mClassName->mSlot)->name); nodePostErrorLine((PyrParseNode*)(mSuperClassName ? mSuperClassName : mClassName)); compileErrors++; } if (indexTypesDiffer) { error("Index type of '%s' does not match intrinsic definition.\n", slotRawSymbol(&mClassName->mSlot)->name); nodePostErrorLine((indexType ? (PyrParseNode*)mIndexType : (PyrParseNode*)mClassName)); compileErrors++; } error("Class '%s' declaration doesn't match intrinsic definition.\n", slotRawSymbol(&mClassName->mSlot)->name); return; } else { shouldRecompileSubclasses = true; } } // reallocate fields in the class object reallocClassObj(metaclassobj, classClassNumInstVars, 0, 0, numClassMethods, indexType, 0); // postfl("^3 %d %d\n", metaclassobj, class_class); // postfl("^4 %d %d\n", slotRawObject(&metaclassobj->iprototype), slotRawObject(&class_class->iprototype)); memcpy(slotRawObject(&metaclassobj->iprototype)->slots, slotRawObject(&class_class->iprototype)->slots, sizeof(PyrSlot) * classClassNumInstVars); memcpy(slotRawSymbolArray(&metaclassobj->instVarNames)->symbols, slotRawSymbolArray(&class_class->instVarNames)->symbols, sizeof(PyrSymbol*) * classClassNumInstVars); slotRawObject(&metaclassobj->iprototype)->size = classClassNumInstVars; slotRawSymbolArray(&metaclassobj->instVarNames)->size = classClassNumInstVars; reallocClassObj(classobj, mVarTally[varInst] + mNumSuperInstVars, mVarTally[varClass], mVarTally[varConst], numInstMethods, indexType, 0); } else { PyrSymbol *superClassName, *metaClassName, *metaSuperClassName; superClassName = superclassobj ? slotRawSymbol(&superclassobj->name) : nullptr; metaClassName = getmetasym(slotRawSymbol(&mClassName->mSlot)->name); metaClassName->flags |= sym_MetaClass; metaSuperClassName = superClassName ? getmetasym(superClassName->name) : nullptr; metaclassobj = newClassObj(class_class, metaClassName, metaSuperClassName, classClassNumInstVars, 0, 0, numClassMethods, indexType, 0); // test // postfl("^1 %d %d\n", metaclassobj, class_class); // postfl("^2 %d %d\n", slotRawObject(&metaclassobj->iprototype), slotRawObject(&class_class->iprototype)); memcpy(slotRawObject(&metaclassobj->iprototype)->slots, slotRawObject(&class_class->iprototype)->slots, sizeof(PyrSlot) * classClassNumInstVars); memcpy(slotRawSymbolArray(&metaclassobj->instVarNames)->symbols, slotRawSymbolArray(&class_class->instVarNames)->symbols, sizeof(PyrSymbol*) * classClassNumInstVars); slotRawObject(&metaclassobj->iprototype)->size = classClassNumInstVars; slotRawObject(&metaclassobj->instVarNames)->size = classClassNumInstVars; // end test classobj = newClassObj(metaclassobj, slotRawSymbol(&mClassName->mSlot), superClassName, mVarTally[varInst] + mNumSuperInstVars, mVarTally[varClass], mVarTally[varConst], numInstMethods, indexType, 0); } gCurrentClass = classobj; gCurrentMetaClass = metaclassobj; if (gCompilingFileSym) { SetSymbol(&classobj->filenameSym, gCompilingFileSym); SetInt(&classobj->charPos, linestarts[mClassName->mLineno] + errCharPosOffset); SetSymbol(&metaclassobj->filenameSym, gCompilingFileSym); SetInt(&metaclassobj->charPos, linestarts[mClassName->mLineno] + errCharPosOffset); } else { SetNil(&classobj->filenameSym); SetNil(&metaclassobj->filenameSym); } // fill inst and class prototypes fillClassPrototypes(this, classobj, superclassobj); // compile methods compileNodeMethods(this); // recompileSubclasses if (shouldRecompileSubclasses) { recompileSubclasses(classobj); } } void recompileSubclasses(PyrClass* classobj) {} #if 0 void catVarLists(PyrVarListNode *varlist); void catVarLists(PyrVarListNode *varlist) { PyrVarListNode *prevvarlist; PyrVarDefNode *vardef, *lastvardef; if (varlist) { // find end of this list vardef = varlist->mVarDefs; for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { lastvardef = vardef; } prevvarlist = varlist; varlist = (PyrVarListNode*)varlist->mNext; for (; varlist; varlist = (PyrVarListNode*)varlist->mNext) { vardef = varlist->mVarDefs; if (lastvardef) { lastvardef->mNext = (PyrParseNode*)vardef; } else { prevvarlist->mVarDefs = vardef; } // find end of this list for (; vardef; vardef = (PyrVarDefNode*)vardef->mNext) { lastvardef = vardef; } } } } #else void catVarLists(PyrVarListNode* varlist); void catVarLists(PyrVarListNode* varlist) { PyrVarListNode* prevvarlist; PyrVarDefNode *vardef, *lastvardef; if (varlist) { // find end of this list vardef = varlist->mVarDefs; lastvardef = (PyrVarDefNode*)vardef->mTail; prevvarlist = varlist; varlist = (PyrVarListNode*)varlist->mNext; for (; varlist; varlist = (PyrVarListNode*)varlist->mNext) { vardef = varlist->mVarDefs; lastvardef->mNext = (PyrParseNode*)vardef; // find end of this list lastvardef = (PyrVarDefNode*)vardef->mTail; } } } #endif PyrMethodNode* newPyrMethodNode(PyrSlotNode* methodName, PyrSlotNode* primitiveName, PyrArgListNode* arglist, PyrVarListNode* varlist, PyrParseNode* body, int isClassMethod) { PyrMethodNode* node = ALLOCNODE(PyrMethodNode); node->mMethodName = methodName; node->mPrimitiveName = primitiveName; node->mArglist = arglist; catVarLists(varlist); node->mVarlist = varlist; node->mBody = body; node->mIsClassMethod = isClassMethod; return node; } enum { push_Normal, push_AllArgs, push_AllButFirstArg, push_AllButFirstArg2 }; int checkPushAllArgs(PyrParseNode* actualArg, int numArgs); int checkPushAllArgs(PyrParseNode* actualArg, int numArgs) { PyrBlock* block; PyrPushNameNode* nameNode; block = gCompilingBlock; int i; // if (strcmp("ar", slotRawSymbol(&gCompilingMethod->name)->name)==0) Debugger(); if (actualArg->mClassno != pn_PushNameNode) { if (numArgs < 3) { return push_Normal; } actualArg = actualArg->mNext; for (i = 1; i < numArgs; ++i) { if (actualArg->mClassno != pn_PushNameNode) { return push_Normal; } nameNode = (PyrPushNameNode*)actualArg; if (slotRawSymbol(&nameNode->mSlot) != slotRawSymbolArray(&block->argNames)->symbols[i]) { return push_Normal; } actualArg = actualArg->mNext; } return push_AllButFirstArg; } else { for (i = 0; i < numArgs; ++i) { if (actualArg->mClassno != pn_PushNameNode) { return push_Normal; } nameNode = (PyrPushNameNode*)actualArg; if (slotRawSymbol(&nameNode->mSlot) != slotRawSymbolArray(&block->argNames)->symbols[i]) { return push_Normal; } actualArg = actualArg->mNext; } return push_AllArgs; } } int checkPushAllButFirstTwoArgs(PyrParseNode* actualArg, int numArgs); int checkPushAllButFirstTwoArgs(PyrParseNode* actualArg, int numArgs) { PyrBlock* block; PyrPushNameNode* nameNode; block = gCompilingBlock; int i; if (numArgs >= 2) { actualArg = actualArg->mNext; actualArg = actualArg->mNext; for (i = 1; i < numArgs; ++i) { if (actualArg->mClassno != pn_PushNameNode) { return push_Normal; } nameNode = (PyrPushNameNode*)actualArg; if (slotRawSymbol(&nameNode->mSlot) != slotRawSymbolArray(&block->argNames)->symbols[i]) { return push_Normal; } actualArg = actualArg->mNext; } return push_AllButFirstArg2; } return push_Normal; } int compareCallArgs(PyrMethodNode* node, PyrCallNode* cnode, int* varIndex, PyrClass** specialClass) { int i, numFormalArgs, numActualArgs; int special, varType, varLevel; PyrParseNode* actualArg; PyrVarDefNode* formalArg; PyrPushNameNode* nameNode; // fail if has a rest arg .. too much trouble? if (node->mArglist && node->mArglist->mRest) { return methNormal; } // check first actual arg is 'this' actualArg = cnode->mArglist; if (actualArg->mClassno != pn_PushNameNode) { return methNormal; } nameNode = (PyrPushNameNode*)actualArg; if (slotRawSymbol(&nameNode->mSlot) == s_this) { special = methRedirect; } else if (slotRawSymbol(&nameNode->mSlot) == s_super) { special = methRedirectSuper; } else { bool varFound; PyrClass* classobj; classobj = gCompilingClass; varFound = findVarName(gCompilingBlock, &classobj, slotRawSymbol(&nameNode->mSlot), &varType, &varLevel, varIndex, nullptr); if (!varFound) return methNormal; if (varType == varInst) special = methForwardInstVar; else if (varType == varClass) { special = methForwardClassVar; *varIndex += slotRawInt(&classobj->classVarIndex); *specialClass = classobj; } else return methNormal; } actualArg = actualArg->mNext; numActualArgs = nodeListLength((PyrParseNode*)cnode->mArglist); if (!node->mArglist) { numFormalArgs = 1; if (numActualArgs != numFormalArgs) { return methNormal; } } else { numFormalArgs = 1 + nodeListLength((PyrParseNode*)node->mArglist->mVarDefs); if (numActualArgs != numFormalArgs) { return methNormal; } formalArg = node->mArglist->mVarDefs; for (i = 0; i < numActualArgs - 1; ++i) { if (actualArg->mClassno != pn_PushNameNode) { return methNormal; } nameNode = (PyrPushNameNode*)actualArg; if (slotRawSymbol(&nameNode->mSlot) != slotRawSymbol(&formalArg->mVarName->mSlot)) { return methNormal; } formalArg = (PyrVarDefNode*)formalArg->mNext; actualArg = actualArg->mNext; } } /* if (special == methForwardInstVar) { postfl("methForwardInstVar %s:%s formal %d actual %d\n", slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, numFormalArgs, numActualArgs); } if (special == methForwardClassVar) { postfl("methForwardClassVar %s:%s formal %d actual %d\n", slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, numFormalArgs, numActualArgs); } if (special == methRedirectSuper) { postfl("methRedirectSuper %s:%s formal %d actual %d\n", slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, numFormalArgs, numActualArgs); } */ // if (special == methTempDelegate) { // postfl("methTempDelegate %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); // } return special; } void installByteCodes(PyrBlock* block) { PyrInt8Array* byteArray; long length, flags; ByteCodes byteCodes; byteCodes = getByteCodes(); if (byteCodes) { length = byteCodeLength(byteCodes); if (length) { flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; byteArray = newPyrInt8Array(compileGC(), length, flags, false); copyByteCodes(byteArray->b, byteCodes); byteArray->size = length; freeByteCodes(byteCodes); SetObject(&block->code, byteArray); } else { error("installByteCodes: zero length byte codes\n"); } } else { error("installByteCodes: NULL byte codes\n"); } } PyrMethod* initPyrMethod(PyrMethod* method); void compilePyrMethodNode(PyrMethodNode* node, PyrSlot* result) { node->compile(result); } void PyrMethodNode::compile(PyrSlot* result) { PyrMethod *method, *oldmethod; PyrMethodRaw* methraw; int i, j, numArgs, numVars, methType, firstKeyIndex; int numVariableArgs = 0; int numKwArgs = 0; int index, numSlots, numArgNames; bool hasPrimitive = false; bool hasVarExprs = false; PyrVarDefNode* vardef; PyrObject* proto; PyrSymbolArray *argNames, *varNames; SetTailBranch branch(false); // postfl("->method '%s'\n", slotRawSymbol(&mMethodName->mSlot)->name); gCompilingClass = mIsClassMethod ? gCurrentMetaClass : gCurrentClass; oldmethod = classFindDirectMethod(gCompilingClass, slotRawSymbol(&mMethodName->mSlot)); if (oldmethod && !mExtension) { error("Method %s:%s already defined.\n", slotRawSymbol(&slotRawClass(&oldmethod->ownerclass)->name)->name, slotRawSymbol(&oldmethod->name)->name); nodePostErrorLine((PyrParseNode*)mMethodName); compileErrors++; return; } if (oldmethod) { ++numOverwrites; // accumulate overwrite message onto the string buffer overwriteMsg.append(slotRawSymbol(&slotRawClass(&oldmethod->ownerclass)->name)->name) .append(":") .append(slotRawSymbol(&oldmethod->name)->name) .append("\t") .append(gCompilingFileSym->name) .append("\t") .append(slotRawSymbol(&oldmethod->filenameSym)->name) .append("\n"); method = oldmethod; freePyrSlot(&method->code); freePyrSlot(&method->selectors); freePyrSlot(&method->prototypeFrame); freePyrSlot(&method->argNames); freePyrSlot(&method->varNames); initPyrMethod(method); } else { method = newPyrMethod(); } SetObject(&method->ownerclass, gCompilingClass); methraw = METHRAW(method); methraw->unused1 = 0; methraw->unused2 = 0; // postfl("method %p raw %p\n", method, methraw); method->contextDef = o_nil; method->name = mMethodName->mSlot; if (gCompilingFileSym) SetSymbol(&method->filenameSym, gCompilingFileSym); SetInt(&method->charPos, linestarts[mMethodName->mLineno] + errCharPosOffset); if (mPrimitiveName) { hasPrimitive = true; method->primitiveName = mPrimitiveName->mSlot; methraw->specialIndex = slotRawSymbol(&mPrimitiveName->mSlot)->u.index; } gCompilingBlock = (PyrBlock*)method; gCompilingMethod = (PyrMethod*)method; gPartiallyAppliedFunction = nullptr; gInliningLevel = 0; methraw->needsHeapContext = 0; methraw->varargs = 0; if (mArglist) { if (mArglist->mRest) { methraw->varargs += 1; numVariableArgs = 1; if (mArglist->mKeywordArgs) { methraw->varargs += 1; numKwArgs = 1; } } } numArgs = mArglist ? nodeListLength((PyrParseNode*)mArglist->mVarDefs) + 1 : 1; numVars = mVarlist ? nodeListLength((PyrParseNode*)mVarlist->mVarDefs) : 0; numSlots = numArgs + numVariableArgs + numKwArgs + numVars; methraw->frameSize = (numSlots + FRAMESIZE) * sizeof(PyrSlot); methraw->numargs = numArgs; methraw->numvars = numVars; methraw->posargs = numArgs + numVariableArgs + numKwArgs; methraw->numtemps = numSlots; methraw->popSize = numSlots - 1; firstKeyIndex = numArgs + numVariableArgs + numKwArgs; numArgNames = methraw->posargs; if (numSlots == 1) { slotCopy(&method->argNames, &o_argnamethis); slotCopy(&method->prototypeFrame, &o_onenilarray); } else { argNames = newPyrSymbolArray(nullptr, numArgNames, obj_permanent | obj_immutable, false); argNames->size = numArgNames; SetObject(&method->argNames, argNames); proto = newPyrArray(nullptr, numSlots, obj_permanent | obj_immutable, false); proto->size = numSlots; SetObject(&method->prototypeFrame, proto); // declare args slotRawSymbolArray(&method->argNames)->symbols[0] = s_this; if (mArglist) { PyrSymbol** methargs; methargs = slotRawSymbolArray(&method->argNames)->symbols; vardef = mArglist->mVarDefs; for (i = 1; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot* varslot; varslot = &vardef->mVarName->mSlot; // already declared as arg? for (j = 0; j < i; ++j) { if (methargs[j] == slotRawSymbol(varslot)) { error("Argument '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in arglist methargs[i] = slotRawSymbol(varslot); // postfl("defarg %d '%s'\n", i, slotRawSymbol(slot)->name); /*if (slotRawSymbol(varslot)->name[0] == 'a' && slotRawSymbol(varslot)->name[1] == 'r' && slotRawSymbol(varslot)->name[2] == 'g') { post("%d %s:%s '%s'\n", i, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, slotRawSymbol(varslot)->name); }*/ } if (numVariableArgs > 0) { PyrSlot* varslot; varslot = &mArglist->mRest->mSlot; // already declared as arg? for (j = 0; j < numArgs; ++j) { if (methargs[j] == slotRawSymbol(varslot)) { error("Argument '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in arglist methargs[i] = slotRawSymbol(varslot); // postfl("defrest '%s'\n", slotRawSymbol(slot)->name); if (numKwArgs > 0) { // 'i' is the variable used in the for loop. Be careful of this! i += 1; PyrSlot* kwvarslot; kwvarslot = &mArglist->mKeywordArgs->mSlot; // already declared as arg? // Add one here to numArgs to include the name of the variableArgument slot for (j = 0; j < numArgs + 1; ++j) { if (methargs[j] == slotRawSymbol(kwvarslot)) { error("Argument '%s' already declared in %s:%s\n", slotRawSymbol(kwvarslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)kwvarslot); compileErrors++; } } methargs[i] = slotRawSymbol(kwvarslot); } } } // fill prototype args if (NotNil(&method->prototypeFrame)) { SetNil(&slotRawObject(&method->prototypeFrame)->slots[0]); } if (mArglist) { vardef = mArglist->mVarDefs; for (i = 1; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot *slot, litval; slot = slotRawObject(&method->prototypeFrame)->slots + i; // compilePyrLiteralNode((PyrLiteralNode*)vardef->mDefVal, &litval); if (vardef->hasExpr(&litval)) hasVarExprs = true; *slot = litval; } if (numVariableArgs > 0) { slotCopy(&slotRawObject(&method->prototypeFrame)->slots[numArgs], &o_emptyarray); if (numKwArgs > 0) { slotCopy(&slotRawObject(&method->prototypeFrame)->slots[numArgs + 1], &o_emptyarray); } } } } if (numVars) { varNames = newPyrSymbolArray(nullptr, numVars, obj_permanent | obj_immutable, false); varNames->size = numVars; SetObject(&method->varNames, varNames); } else { SetNil(&method->varNames); } // declare vars if (mVarlist) { PyrSymbol **methargs, **methvars; methargs = slotRawSymbolArray(&method->argNames)->symbols; methvars = slotRawSymbolArray(&method->varNames)->symbols; vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot* varslot; varslot = &vardef->mVarName->mSlot; // already declared as arg? for (j = 0; j < numArgNames; ++j) { if (methargs[j] == slotRawSymbol(varslot)) { error("Variable '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // already declared as var? for (j = 0; j < i; ++j) { if (methvars[j] == slotRawSymbol(varslot)) { error("Variable '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in mVarlist methvars[i] = slotRawSymbol(varslot); // postfl("defvar %d '%s'\n", i, slotRawSymbol(slot)->name); } } if (mVarlist) { vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot *slot, litval; slot = slotRawObject(&method->prototypeFrame)->slots + i + numArgs + numVariableArgs + numKwArgs; if (vardef->hasExpr(&litval)) hasVarExprs = true; // compilePyrLiteralNode(vardef->mDefVal, &litval); *slot = litval; } } methType = methNormal; if (hasVarExprs) { methType = methNormal; } else if (hasPrimitive) { methType = methPrimitive; /* if (getPrimitiveNumArgs(methraw->specialIndex) != numArgs) { post("warning: number of arguments for method %s:%s does not match primitive %s. %d vs %d\n", slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name, getPrimitiveName(methraw->specialIndex)->name, numArgs, getPrimitiveNumArgs(methraw->specialIndex)); } */ } else if (slotRawSymbol(&gCompilingMethod->name) == s_doesNotUnderstand) { methType = methNormal; } else { int bodyType = mBody->mClassno; if (bodyType == pn_ReturnNode) { PyrReturnNode* rnode; PyrParseNode* xnode; int rtype; PyrSlot rslot; rnode = (PyrReturnNode*)mBody; xnode = (PyrParseNode*)rnode->mExpr; if (xnode) { rtype = xnode->mClassno; if (rtype == pn_PushLitNode) { // return literal ? compilePyrLiteralNode((PyrLiteralNode*)xnode, &rslot); if (IsObj(&rslot) && slotRawObject(&rslot)->classptr == class_fundef) { methType = methNormal; } else { methType = methReturnLiteral; method->selectors = rslot; } } else if (rtype == pn_PushNameNode) { PyrSlot* rslot; rslot = &((PyrPushNameNode*)xnode)->mSlot; if (slotRawSymbol(rslot) == s_this) { // return this methType = methReturnSelf; } else { if (funcFindArg((PyrBlock*)method, slotRawSymbol(rslot), &index)) { // return arg ? // eliminate the case where its an ellipsis or keyword argument if (index < methraw->numargs) { methType = methReturnArg; methraw->specialIndex = index; // when you change sp to sp - 1 // methraw->specialIndex = index - 1; } } else if (classFindInstVar(gCompilingClass, slotRawSymbol(rslot), &index)) { // return inst var methType = methReturnInstVar; methraw->specialIndex = index; } } } else if (rtype == pn_CallNode) { // need to do this for binary opcodes too.. int specialIndex; PyrCallNode* cnode; PyrClass* specialClass = nullptr; cnode = (PyrCallNode*)xnode; methType = compareCallArgs(this, cnode, &specialIndex, &specialClass); if (methType != methNormal) { methraw->specialIndex = specialIndex; method->selectors = cnode->mSelector->mSlot; if (specialClass) method->constants = specialClass->name; } } } else { methType = methReturnSelf; } } else if (bodyType == pn_AssignNode && numArgs == 2) { // assign inst var ? PyrAssignNode* anode; // post("methAssignInstVar 1 %s:%s\n", // slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); anode = (PyrAssignNode*)mBody; if (anode->mNext && anode->mNext->mClassno == pn_ReturnNode && ((PyrReturnNode*)anode->mNext)->mExpr == nullptr) { // post("methAssignInstVar 2 %s:%s\n", // slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); if (classFindInstVar(gCompilingClass, slotRawSymbol(&anode->mVarName->mSlot), &index)) { methType = methAssignInstVar; methraw->specialIndex = index; // post("methAssignInstVar 3 %s:%s\n", // slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); } } } } methraw->methType = methType; // set primitive // optimize common cases if (methType == methNormal || methType == methPrimitive) { PyrSlot dummy; PyrSymbol* name; // compile body initByteCodes(); if (gCompilingClass == class_int) { // handle some special cases name = slotRawSymbol(&method->name); if (name == gSpecialSelectors[opmDo]) { compileByte(143); compileByte(0); compileByte(143); compileByte(1); } else if (name == gSpecialSelectors[opmReverseDo]) { compileByte(143); compileByte(2); compileByte(143); compileByte(3); compileByte(143); compileByte(4); } else if (name == gSpecialSelectors[opmFor]) { compileByte(143); compileByte(5); compileByte(143); compileByte(6); compileByte(143); compileByte(16); } else if (name == gSpecialSelectors[opmForBy]) { compileByte(143); compileByte(7); compileByte(143); compileByte(8); compileByte(143); compileByte(9); } else goto compile_body; } else if (gCompilingClass == class_arrayed_collection) { name = slotRawSymbol(&method->name); if (name == gSpecialSelectors[opmDo]) { compileByte(143); compileByte(10); compileByte(143); compileByte(1); } else if (name == gSpecialSelectors[opmReverseDo]) { compileByte(143); compileByte(11); compileByte(143); compileByte(12); compileByte(143); compileByte(4); } else goto compile_body; } else if (slotRawSymbol(&gCompilingClass->name) == s_dictionary) { name = slotRawSymbol(&method->name); if (name == getsym("keysValuesArrayDo")) { compileByte(143); compileByte(13); compileByte(143); compileByte(14); } else goto compile_body; } else if (gCompilingClass == class_number) { name = slotRawSymbol(&method->name); if (name == gSpecialSelectors[opmForSeries]) { compileByte(143); compileByte(29); compileByte(143); compileByte(30); compileByte(143); compileByte(31); } else goto compile_body; } else if (gCompilingClass == class_float) { // handle some special cases name = slotRawSymbol(&method->name); if (name == gSpecialSelectors[opmDo]) { compileByte(143); compileByte(17); compileByte(143); compileByte(18); } else if (name == gSpecialSelectors[opmReverseDo]) { compileByte(143); compileByte(19); compileByte(143); compileByte(20); compileByte(143); compileByte(21); } else goto compile_body; } else { compile_body: SetTailIsMethodReturn mr(false); if (mArglist) { vardef = mArglist->mVarDefs; for (i = 1; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { vardef->compileArg(&dummy); } } if (mVarlist) { vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { vardef->compile(&dummy); } } COMPILENODE(mBody, &dummy, true); } installByteCodes((PyrBlock*)method); } if (!oldmethod) { addMethod(gCompilingClass, method); } gCompilingMethod = nullptr; gCompilingBlock = nullptr; gPartiallyAppliedFunction = nullptr; // postfl("<-method '%s'\n", slotRawSymbol(&mMethodName->mSlot)->name); } PyrArgListNode* newPyrArgListNode(PyrVarDefNode* varDefs, PyrSlotNode* rest, PyrSlotNode* kwArgs) { auto* node = ALLOCNODE(PyrArgListNode); node->mVarDefs = varDefs; node->mRest = rest; node->mKeywordArgs = kwArgs; return node; } void PyrArgListNode::compile(PyrSlot* result) { error("compilePyrArgListNode: shouldn't get here.\n"); compileErrors++; } PyrVarListNode* newPyrVarListNode(PyrVarDefNode* vardefs, int flags) { PyrVarListNode* node = ALLOCNODE(PyrVarListNode); node->mVarDefs = vardefs; node->mFlags = flags; return node; } void PyrVarListNode::compile(PyrSlot* result) { error("compilePyrVarListNode: shouldn't get here.\n"); compileErrors++; } PyrVarDefNode* newPyrVarDefNode(PyrSlotNode* varName, PyrParseNode* defVal, int flags) { PyrVarDefNode* node = ALLOCNODE(PyrVarDefNode); node->mVarName = varName; node->mDefVal = defVal; node->mFlags = flags; node->mDrop = true; return node; } bool PyrVarDefNode::hasExpr(PyrSlot* result) { if (result) SetNil(result); if (!mDefVal) return false; if (mDefVal->mClassno != pn_PushLitNode && mDefVal->mClassno != pn_LiteralNode) { // post("hasExpr A %s:%s %s %d\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name, mVarName->slotRawSymbol(&mSlot)->name, mDefVal->mClassno); return true; } PyrPushLitNode* node = (PyrPushLitNode*)mDefVal; if (IsPtr(&node->mSlot)) { PyrParseNode* litnode = (PyrParseNode*)slotRawPtr(&node->mSlot); if (litnode) { if (litnode->mClassno == pn_BlockNode) { // post("hasExpr B %s:%s %s %d\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name, mVarName->slotRawSymbol(&mSlot)->name, node->mClassno); return true; } else { if (result) node->compileLiteral(result); } } } else if (result) *result = node->mSlot; if (node->mParens) return true; return false; } void PyrVarDefNode::compile(PyrSlot* result) { if (hasExpr(nullptr)) { COMPILENODE(mDefVal, result, false); compileAssignVar((PyrParseNode*)this, slotRawSymbol(&mVarName->mSlot), mDrop); } // error("compilePyrVarDefNode: shouldn't get here.\n"); // compileErrors++; } void PyrVarDefNode::compileArg(PyrSlot* result) { if (hasExpr(nullptr)) { ByteCodes trueByteCodes; compilePushVar((PyrParseNode*)this, slotRawSymbol(&mVarName->mSlot)); mDrop = false; trueByteCodes = compileBodyWithGoto(this, 0, true); int jumplen = byteCodeLength(trueByteCodes); compileByte(143); // special opcodes compileByte(26); compileByte((jumplen >> 8) & 0xFF); compileByte(jumplen & 0xFF); compileAndFreeByteCodes(trueByteCodes); compileOpcode(opSpecialOpcode, opcDrop); // drop the boolean } // error("compilePyrVarDefNode: shouldn't get here.\n"); // compileErrors++; } PyrCallNode* newPyrCallNode(PyrSlotNode* selector, PyrParseNode* arglist, PyrParseNode* keyarglist, PyrParseNode* blocklist) { PyrCallNode* node = ALLOCNODE(PyrCallNode); node->mSelector = selector; arglist = linkNextNode(arglist, blocklist); node->mArglist = arglist; node->mKeyarglist = keyarglist; return node; } int PyrCallNode::isPartialApplication() { int sum = 0; PyrParseNode* argnode = mArglist; for (; argnode; argnode = argnode->mNext) { if (argnode->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)argnode)->mArgNum = sum; sum++; } } PyrParseNode* keynode = mKeyarglist; for (; keynode; keynode = keynode->mNext) { if (keynode->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)keynode)->mArgNum = sum; sum++; } } return sum; } void PyrCallNodeBase::compilePartialApplication(int numCurryArgs, PyrSlot* result) { // create a function // compile the call ByteCodes savedBytes = saveByteCodeArray(); int flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; PyrBlock* block = newPyrBlock(flags); PyrSlot blockSlot; SetObject(&blockSlot, block); int prevFunctionHighestExternalRef = gFunctionHighestExternalRef; bool prevFunctionCantBeClosed = gFunctionCantBeClosed; gFunctionHighestExternalRef = 0; gFunctionCantBeClosed = false; PyrClass* prevClass = gCompilingClass; PyrBlock* prevBlock = gCompilingBlock; gCompilingBlock = block; PyrBlock* prevPartiallyAppliedFunction = gPartiallyAppliedFunction; gPartiallyAppliedFunction = block; PyrMethodRaw* methraw = METHRAW(block); methraw->unused1 = 0; methraw->unused2 = 0; methraw->needsHeapContext = 0; SetObject(&block->contextDef, prevBlock); //// methraw->varargs = 0; methraw->frameSize = (numCurryArgs + FRAMESIZE) * sizeof(PyrSlot); PyrObject* proto = newPyrArray(compileGC(), numCurryArgs, flags, false); proto->size = numCurryArgs; SetObject(&block->prototypeFrame, proto); PyrSymbolArray* argNames = newPyrSymbolArray(compileGC(), numCurryArgs, flags, false); argNames->size = numCurryArgs; SetObject(&block->argNames, argNames); SetNil(&block->varNames); methraw->numargs = numCurryArgs; methraw->numvars = 0; methraw->posargs = numCurryArgs; methraw->numtemps = numCurryArgs; methraw->popSize = numCurryArgs; methraw->methType = methBlock; { PyrSymbol* s_empty = getsym("_"); PyrSymbol** blockargs = slotRawSymbolArray(&block->argNames)->symbols; for (int i = 0; i < numCurryArgs; ++i) { // put it in mArglist blockargs[i] = s_empty; SetNil(proto->slots + i); } } initByteCodes(); { SetTailBranch branch(true); SetTailIsMethodReturn mr(false); PyrSlot body; compileCall(&body); } compileOpcode(opSpecialOpcode, opcFunctionReturn); installByteCodes(block); gCompilingBlock = prevBlock; gPartiallyAppliedFunction = prevPartiallyAppliedFunction; restoreByteCodeArray(savedBytes); int index = conjureLiteralSlotIndex(this, gCompilingBlock, &blockSlot); compileOpcode(opExtended, opPushLiteral); compileByte(index); if (!gFunctionCantBeClosed && gFunctionHighestExternalRef == 0) { SetNil(&block->contextDef); } else { METHRAW(prevBlock)->needsHeapContext = 1; } gCompilingBlock = prevBlock; gCompilingClass = prevClass; gPartiallyAppliedFunction = prevPartiallyAppliedFunction; gFunctionCantBeClosed = gFunctionCantBeClosed || prevFunctionCantBeClosed; gFunctionHighestExternalRef = sc_max(gFunctionHighestExternalRef - 1, prevFunctionHighestExternalRef); } void PyrCallNodeBase::compile(PyrSlot* result) { int numCurryArgs = isPartialApplication(); if (numCurryArgs) { compilePartialApplication(numCurryArgs, result); } else { compileCall(result); } } bool isSeries(PyrParseNode* node, PyrParseNode** args) { if (node->mClassno != pn_CallNode) return false; PyrCallNode* callnode = (PyrCallNode*)node; if (slotRawSymbol(&callnode->mSelector->mSlot) != s_series) return false; if (callnode->mKeyarglist) return false; *args = callnode->mArglist; return true; } void PyrCallNode::compileCall(PyrSlot* result) { int index, selType; PyrSlot dummy; bool varFound; PyrParseNode* argnode2; // postfl("compilePyrCallNode\n"); PyrParseNode* argnode = mArglist; PyrParseNode* keynode = mKeyarglist; int numArgs = nodeListLength(argnode); int numKeyArgs = nodeListLength(keynode); int isSuper = isSuperObjNode(argnode); int numBlockArgs = METHRAW(gCompilingBlock)->numargs; slotRawSymbol(&mSelector->mSlot)->flags |= sym_Called; index = conjureSelectorIndex((PyrParseNode*)mSelector, gCompilingBlock, isSuper, slotRawSymbol(&mSelector->mSlot), &selType); if (numKeyArgs > 0 || (numArgs > 15 && !(selType == selSwitch || selType == selCase))) { for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } for (; keynode; keynode = keynode->mNext) { COMPILENODE(keynode, &dummy, false); } if (isSuper) { compileTail(); compileByte(opSendSuper); compileByte(numArgs + 2 * numKeyArgs); compileByte(numKeyArgs); compileByte(index); } else { switch (selType) { case selNormal: compileTail(); compileByte(opSendMsg); compileByte(numArgs + 2 * numKeyArgs); compileByte(numKeyArgs); compileByte(index); break; case selSpecial: compileTail(); compileByte(opSendSpecialMsg); compileByte(numArgs + 2 * numKeyArgs); compileByte(numKeyArgs); compileByte(index); break; case selUnary: case selBinary: index = conjureLiteralSlotIndex((PyrParseNode*)mSelector, gCompilingBlock, &mSelector->mSlot); // fall through default: compileTail(); compileByte(opSendMsg); compileByte(numArgs + 2 * numKeyArgs); compileByte(numKeyArgs); compileByte(index); break; } } } else if (isSuper) { if (numArgs == 1) { // pushes this as well, don't compile arg gFunctionCantBeClosed = true; compileTail(); compileOpcode(opSendSuper, numArgs); compileByte(index); } else { for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSuper, numArgs); compileByte(index); } } else { PyrSymbol* varname; if (argnode->mClassno == pn_PushNameNode) { varname = slotRawSymbol(&((PyrPushNameNode*)argnode)->mSlot); } else { varname = nullptr; } if (varname == s_this) { gFunctionCantBeClosed = true; } switch (selType) { case selNormal: if (numArgs == 1 && varname == s_this) { compileTail(); compileOpcode(opSendMsg, 0); compileByte(index); //} else if (numArgs>1 && numArgs == numBlockArgs) { } else if (numArgs > 1 && numArgs == numBlockArgs) { // try for multiple push optimization int code; code = checkPushAllArgs(argnode, numArgs); if (code == push_Normal) goto normal; else if (code == push_AllArgs) { compileTail(); compileByte(137); // push all args, send msg compileByte(index); // post("137 pushAllArgs %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else if (code == push_AllButFirstArg) { COMPILENODE(argnode, &dummy, false); compileTail(); compileByte(138); // push all but first arg, send msg compileByte(index); // post("138 pushAllButFirstArg %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else goto normal; } else if (numArgs > 2 && numArgs == numBlockArgs + 1) { int code; code = checkPushAllButFirstTwoArgs(argnode, numBlockArgs); if (code == push_Normal) goto normal; else if (code == push_AllButFirstArg2) { COMPILENODE(argnode, &dummy, false); COMPILENODE(argnode->mNext, &dummy, false); compileTail(); compileByte(141); // one arg pushed, push all but first arg, send msg compileByte(index); // post("141 pushAllButFirstArg2 %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else goto normal; } else { normal: for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendMsg, numArgs); compileByte(index); } break; case selSpecial: if (numArgs == 1) { if (varname == s_this) { compileTail(); compileOpcode(opSendSpecialMsg, 0); compileByte(index); } else if (varname) { PyrClass* classobj; PyrBlock* tempFunc; int varType, varLevel, varIndex; classobj = gCompilingClass; varFound = findVarName(gCompilingBlock, &classobj, varname, &varType, &varLevel, &varIndex, &tempFunc); if (varFound && varType == varInst) { // post("136 pushInstVar(sp) %s:%s '%s' %d %d\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name, varname->name, varIndex, index); compileTail(); compileByte(136); compileByte(varIndex); compileByte(index); } else goto special; } else goto special; } else if (index == opmDo && isSeries(argnode, &argnode)) { index = opmForSeries; mArglist = linkNextNode(argnode, mArglist->mNext); numArgs = nodeListLength(mArglist); goto special; } else if (numArgs > 1 && numArgs == numBlockArgs) { //} else if (numArgs>1 && numArgs == numBlockArgs) { // try for multiple push optimization int code; code = checkPushAllArgs(argnode, numArgs); if (code == push_Normal) goto special; else if (code == push_AllArgs) { compileTail(); compileByte(139); // push all args, send special msg compileByte(index); // post("139 pushAllArgs(sp) %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else if (code == push_AllButFirstArg) { COMPILENODE(argnode, &dummy, false); compileTail(); compileByte(140); // push all but first arg, send special msg compileByte(index); // post("140 pushAllButFirstArg(sp) %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else goto special; } else if (numArgs > 2 && numArgs == numBlockArgs + 1) { int code; code = checkPushAllButFirstTwoArgs(argnode, numBlockArgs); if (code == push_Normal) goto special; else if (code == push_AllButFirstArg2) { COMPILENODE(argnode, &dummy, false); COMPILENODE(argnode->mNext, &dummy, false); compileTail(); compileByte(142); // one arg pushed, push all but first arg, send msg compileByte(index); // post("142 pushAllButFirstArg2(sp) %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, // slotRawSymbol(&gCompilingMethod->name)->name); } else goto special; } else { int i; special: for (i = 0; argnode; argnode = argnode->mNext, i++) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(index); } break; case selUnary: if (numArgs != 1) { index = conjureLiteralSlotIndex((PyrParseNode*)mSelector, gCompilingBlock, &mSelector->mSlot); goto defaultCase; } for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialUnaryArithMsg, index); break; case selBinary: if (numArgs != 2) { index = conjureLiteralSlotIndex((PyrParseNode*)mSelector, gCompilingBlock, &mSelector->mSlot); goto defaultCase; } // for (; argnode; argnode = argnode->mNext) { // COMPILENODE(argnode, &dummy, false); //} argnode2 = argnode->mNext; if (index == opAdd && argnode2->mClassno == pn_PushLitNode && IsInt(&((PyrPushLitNode*)argnode2)->mSlot) && slotRawInt(&((PyrPushLitNode*)argnode2)->mSlot) == 1) { COMPILENODE(argnode, &dummy, false); compileOpcode(opPushSpecialValue, opsvPlusOne); } else if (index == opSub && argnode2->mClassno == pn_PushLitNode && IsInt(&((PyrPushLitNode*)argnode2)->mSlot) && slotRawInt(&((PyrPushLitNode*)argnode2)->mSlot) == 1) { COMPILENODE(argnode, &dummy, false); compileOpcode(opPushSpecialValue, opsvMinusOne); } else { COMPILENODE(argnode, &dummy, false); COMPILENODE(argnode->mNext, &dummy, false); compileTail(); compileOpcode(opSendSpecialBinaryArithMsg, index); } break; case selIf: compileAnyIfMsg(this); break; case selCase: compileCaseMsg(this); break; case selSwitch: compileSwitchMsg(this); break; case selWhile: compileWhileMsg(this); break; case selLoop: compileLoopMsg(this); break; case selAnd: if (numArgs == 2) compileAndMsg(argnode, argnode->mNext); else goto special; break; case selOr: if (numArgs == 2) compileOrMsg(argnode, argnode->mNext); else goto special; break; case selQuestionMark: if (numArgs == 2) compileQMsg(argnode, argnode->mNext); break; case selDoubleQuestionMark: if (numArgs == 2) compileQQMsg(argnode, argnode->mNext); break; case selExclamationQuestionMark: if (numArgs == 2) compileXQMsg(argnode, argnode->mNext); break; default: defaultCase: if (numArgs == 1 && varname == s_this) { compileTail(); compileOpcode(opSendMsg, 0); compileByte(index); } else { for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendMsg, numArgs); compileByte(index); } break; } } } ByteCodes compileSubExpression(PyrPushLitNode* litnode, bool onTailBranch) { return compileSubExpressionWithGoto(litnode, 0, onTailBranch); } ByteCodes compileSubExpressionWithGoto(PyrPushLitNode* litnode, int branchLen, bool onTailBranch) { PyrBlockNode* bnode = (PyrBlockNode*)slotRawPtr(&litnode->mSlot); return compileBodyWithGoto(bnode->mBody, branchLen, onTailBranch); } ByteCodes compileBodyWithGoto(PyrParseNode* body, int branchLen, bool onTailBranch) { ByteCodes currentByteCodes, subExprByteCodes; PyrSlot dummy; PyrBlock* prevPartiallyAppliedFunction = gPartiallyAppliedFunction; gPartiallyAppliedFunction = nullptr; currentByteCodes = saveByteCodeArray(); COMPILENODE(body, &dummy, onTailBranch); if (branchLen) { if (!byteCodeLength(gCompilingByteCodes)) { compileOpcode(opPushSpecialValue, opsvNil); // push nil } compileJump(opcJumpFwd, branchLen); } subExprByteCodes = getByteCodes(); restoreByteCodeArray(currentByteCodes); gPartiallyAppliedFunction = prevPartiallyAppliedFunction; return subExprByteCodes; } #if 0 ByteCodes compileDefaultValue(int litIndex, int realExprLen) { ByteCodes currentByteCodes, defaultByteCodes; currentByteCodes = saveByteCodeArray(); compileOpcode(opPushSpecialValue, litIndex); compileJump(realExprLen, unconditionalJump); defaultByteCodes = getByteCodes(); restoreByteCodeArray(currentByteCodes); return (defaultByteCodes); } #endif bool isAnInlineableBlock(PyrParseNode* node) { bool res = false; if (node->mClassno == pn_PushLitNode) { PyrPushLitNode* anode; PyrBlockNode* bnode; anode = (PyrPushLitNode*)node; if (IsPtr(&anode->mSlot) && (bnode = (PyrBlockNode*)(slotRawPtr(&anode->mSlot)))->mClassno == pn_BlockNode) { if (bnode->mArglist || bnode->mVarlist) { if (SC_LanguageConfig::getPostInlineWarnings()) { post("WARNING: FunctionDef contains variable declarations and so" " will not be inlined.\n"); if (bnode->mArglist) nodePostErrorLine((PyrParseNode*)bnode->mArglist); else nodePostErrorLine((PyrParseNode*)bnode->mVarlist); } } else res = true; } } return res; } bool isAnInlineableAtomicLiteralBlock(PyrParseNode* node) { bool res = false; if (node->mClassno == pn_PushLitNode) { PyrPushLitNode* anode; PyrBlockNode* bnode; anode = (PyrPushLitNode*)node; if (IsPtr(&anode->mSlot) && (bnode = (PyrBlockNode*)(slotRawPtr(&anode->mSlot)))->mClassno == pn_BlockNode) { if (bnode->mArglist || bnode->mVarlist) { if (SC_LanguageConfig::getPostInlineWarnings()) { post("WARNING: FunctionDef contains variable declarations and so" " will not be inlined.\n"); if (bnode->mArglist) nodePostErrorLine((PyrParseNode*)bnode->mArglist); else nodePostErrorLine((PyrParseNode*)bnode->mVarlist); } } else { if (bnode->mBody->mClassno == pn_DropNode && ((PyrDropNode*)bnode->mBody)->mExpr2->mClassno == pn_BlockReturnNode) res = isAtomicLiteral(((PyrDropNode*)bnode->mBody)->mExpr1); else res = false; } } } return res; } bool isAtomicLiteral(PyrParseNode* node) { bool res = false; if (node->mClassno == pn_PushLitNode) { PyrPushLitNode* anode; anode = (PyrPushLitNode*)node; if (NotObj(&anode->mSlot) && !IsPtr(&anode->mSlot)) res = true; } return res; } bool isWhileTrue(PyrParseNode* node) { bool res = false; if (node->mClassno == pn_PushLitNode) { PyrPushLitNode* anode; PyrBlockNode* bnode; anode = (PyrPushLitNode*)node; if (IsPtr(&anode->mSlot) && (bnode = (PyrBlockNode*)(slotRawPtr(&anode->mSlot)))->mClassno == pn_BlockNode) { if (bnode->mArglist || bnode->mVarlist) { /* post("WARNING: FunctionDef contains variable declarations and so" " will not be inlined.\n"); if (bnode->mArglist) nodePostErrorLine((PyrParseNode*)bnode->mArglist); else nodePostErrorLine((PyrParseNode*)bnode->mVarlist); */ } else { if (bnode->mBody->mClassno == pn_PushLitNode && IsTrue(&((PyrPushLitNode*)bnode->mBody)->mSlot)) { res = true; } } } else if (IsTrue(&anode->mSlot)) { res = true; } } return res; } void compileAndMsg(PyrParseNode* arg1, PyrParseNode* arg2) { PyrSlot dummy; ByteCodes trueByteCodes; COMPILENODE(arg1, &dummy, false); if (isAnInlineableBlock(arg2)) { trueByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); compileJump(opcJumpIfFalsePushFalse, byteCodeLength(trueByteCodes)); compileAndFreeByteCodes(trueByteCodes); } else { COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, 2); compileByte(opmAnd); } } void compileOrMsg(PyrParseNode* arg1, PyrParseNode* arg2) { PyrSlot dummy; ByteCodes falseByteCodes; COMPILENODE(arg1, &dummy, false); if (isAnInlineableBlock(arg2)) { falseByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); compileJump(opcJumpIfTruePushTrue, byteCodeLength(falseByteCodes)); compileAndFreeByteCodes(falseByteCodes); } else { COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, 2); compileByte(opmOr); } } void compileQMsg(PyrParseNode* arg1, PyrParseNode* arg2) { // question mark. PyrSlot dummy; COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); compileByte(143); // special opcodes compileByte(22); // ?? } void compileQQMsg(PyrParseNode* arg1, PyrParseNode* arg2) { // double question mark. ?? {|obj| ^if (this.notNil, this, func) } PyrSlot dummy; COMPILENODE(arg1, &dummy, false); if (isAnInlineableBlock(arg2)) { ByteCodes nilByteCodes; nilByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); int jumplen = byteCodeLength(nilByteCodes); compileByte(143); // special opcodes compileByte(23); // ?? compileByte((jumplen >> 8) & 0xFF); compileByte(jumplen & 0xFF); compileAndFreeByteCodes(nilByteCodes); } else { COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, 2); compileByte(opmDoubleQuestionMark); } } void compileXQMsg(PyrParseNode* arg1, PyrParseNode* arg2) { // double question mark. !? {|obj| ^if (this.isNil, this, func) } PyrSlot dummy; COMPILENODE(arg1, &dummy, false); if (isAnInlineableBlock(arg2)) { ByteCodes nilByteCodes; nilByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); int jumplen = byteCodeLength(nilByteCodes); compileByte(143); // special opcodes compileByte(27); // !? compileByte((jumplen >> 8) & 0xFF); compileByte(jumplen & 0xFF); compileAndFreeByteCodes(nilByteCodes); } else { COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, 2); compileByte(opmExclamationQuestionMark); } } void compileAnyIfMsg(PyrCallNodeBase2* node) { PyrParseNode* arg1 = node->mArglist; if (arg1->mClassno == pn_CallNode) { PyrCallNode* callNode = (PyrCallNode*)arg1; int numCallArgs = nodeListLength(callNode->mArglist); int numCallKeyArgs = nodeListLength(callNode->mKeyarglist); if (numCallArgs == 1 && numCallKeyArgs == 0) { if (slotRawSymbol(&callNode->mSelector->mSlot) == gSpecialUnarySelectors[opIsNil]) { compileIfNilMsg(node, true); return; } else if (slotRawSymbol(&callNode->mSelector->mSlot) == gSpecialUnarySelectors[opNotNil]) { compileIfNilMsg(node, false); return; } } } compileIfMsg(node); } void compileIfMsg(PyrCallNodeBase2* node) { PyrSlot dummy; ByteCodes trueByteCodes, falseByteCodes; int numArgs = nodeListLength(node->mArglist); PyrParseNode* arg1 = node->mArglist; PyrParseNode *arg2, *arg3; if (numArgs == 2) { arg2 = arg1->mNext; if (isAnInlineableBlock(arg2)) { COMPILENODE(arg1, &dummy, false); trueByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); if (byteCodeLength(trueByteCodes)) { compileJump(opcJumpIfFalsePushNil, byteCodeLength(trueByteCodes)); compileAndFreeByteCodes(trueByteCodes); } else { compileOpcode(opSpecialOpcode, opcDrop); // drop the boolean compileOpcode(opPushSpecialValue, opsvNil); // push nil } } else goto unoptimized; } else if (numArgs == 3) { arg2 = arg1->mNext; arg3 = arg2->mNext; if (isAnInlineableBlock(arg2) && isAnInlineableBlock(arg3)) { COMPILENODE(arg1, &dummy, false); falseByteCodes = compileSubExpression((PyrPushLitNode*)arg3, true); trueByteCodes = compileSubExpressionWithGoto((PyrPushLitNode*)arg2, byteCodeLength(falseByteCodes), true); if (byteCodeLength(falseByteCodes)) { compileJump(opcJumpIfFalse, byteCodeLength(trueByteCodes)); compileAndFreeByteCodes(trueByteCodes); compileAndFreeByteCodes(falseByteCodes); } else if (byteCodeLength(trueByteCodes)) { compileJump(opcJumpIfFalsePushNil, byteCodeLength(trueByteCodes)); compileAndFreeByteCodes(trueByteCodes); } else { compileOpcode(opSpecialOpcode, opcDrop); // drop the boolean compileOpcode(opPushSpecialValue, opsvNil); // push nil } } else goto unoptimized; } else { unoptimized: for (; arg1; arg1 = arg1->mNext) { COMPILENODE(arg1, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmIf); } } void compileIfNilMsg(PyrCallNodeBase2* node, bool flag) { PyrSlot dummy; ByteCodes trueByteCodes, falseByteCodes; PyrParseNode *arg2, *arg3; int numArgs = nodeListLength(node->mArglist); PyrParseNode* arg1 = node->mArglist; if (numArgs < 2) { COMPILENODE(arg1, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmIf); } else if (numArgs == 2) { arg2 = arg1->mNext; if (isAnInlineableBlock(arg2)) { PyrCallNode* callNode = (PyrCallNode*)arg1; COMPILENODE(callNode->mArglist, &dummy, false); trueByteCodes = compileSubExpression((PyrPushLitNode*)arg2, true); int jumplen = byteCodeLength(trueByteCodes); if (jumplen) { compileByte(143); // special opcodes compileByte(flag ? 26 : 27); compileByte((jumplen >> 8) & 0xFF); compileByte(jumplen & 0xFF); compileAndFreeByteCodes(trueByteCodes); } else { compileOpcode(opSpecialOpcode, opcDrop); // drop the value compileOpcode(opPushSpecialValue, opsvNil); // push nil } } else { COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmIf); } } else if (numArgs == 3) { arg2 = arg1->mNext; arg3 = arg2->mNext; if (isAnInlineableBlock(arg2) && isAnInlineableBlock(arg3)) { PyrCallNode* callNode = (PyrCallNode*)arg1; COMPILENODE(callNode->mArglist, &dummy, false); falseByteCodes = compileSubExpression((PyrPushLitNode*)arg3, true); int falseLen = byteCodeLength(falseByteCodes); trueByteCodes = compileSubExpressionWithGoto((PyrPushLitNode*)arg2, falseLen, true); int trueLen = byteCodeLength(trueByteCodes); if (falseLen) { compileByte(143); // special opcodes compileByte(flag ? 24 : 25); compileByte((trueLen >> 8) & 0xFF); compileByte(trueLen & 0xFF); compileAndFreeByteCodes(trueByteCodes); compileAndFreeByteCodes(falseByteCodes); } else if (trueLen) { compileByte(143); // special opcodes compileByte(flag ? 26 : 27); compileByte((trueLen >> 8) & 0xFF); compileByte(trueLen & 0xFF); compileAndFreeByteCodes(trueByteCodes); } else { compileOpcode(opSpecialOpcode, opcDrop); // drop the boolean compileOpcode(opPushSpecialValue, opsvNil); // push nil } } else { COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmIf); } } else { for (; arg1; arg1 = arg1->mNext) { COMPILENODE(arg1, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmIf); } } PyrParseNode* reverseNodeList(PyrParseNode** list) { PyrParseNode* temp1 = *list; PyrParseNode* temp2 = nullptr; PyrParseNode* temp3 = nullptr; while (temp1) { *list = temp1; temp2 = temp1->mNext; temp1->mNext = temp3; temp3 = temp1; temp1 = temp2; } return *list; } PyrCallNode* buildCase(PyrParseNode* arg1) { // transform case statement into nested if statements. // int numArgs = nodeListLength(arg1); // post("->buildCase %d\n", numArgs); PyrParseNode* arg2 = arg1->mNext; PyrPushLitNode* litnode = (PyrPushLitNode*)arg1; PyrBlockNode* bnode = (PyrBlockNode*)slotRawPtr(&litnode->mSlot); PyrParseNode* bbody = bnode->mBody; if (bbody->mClassno == pn_DropNode) { PyrDropNode* dropNode = (PyrDropNode*)bbody; if (dropNode->mExpr2->mClassno == pn_BlockReturnNode) { arg1 = dropNode->mExpr1; } else { arg1 = dropNode; } } else { arg1 = bbody; } arg1->mNext = arg2; PyrParseNode* arg3 = nullptr; if (arg2) { arg3 = arg2->mNext; if (arg3) { PyrParseNode* arg4 = arg3->mNext; if (arg4) { arg3 = buildCase(arg3); PyrBlockNode* bnode = newPyrBlockNode(nullptr, nullptr, arg3, false); arg3 = newPyrPushLitNode(nullptr, bnode); arg2->mNext = arg3; arg3->mNext = nullptr; arg1->mTail = arg3; } } else { arg1->mTail = arg2; } } else { arg1->mTail = arg1; } /* post("arg1->mNext %p arg2 %p\n", arg1->mNext, arg2); if (arg2) { post("arg2->mNext %p arg3 %p\n", arg2->mNext, arg3); post("isAnInlineableBlock arg2 %d\n", isAnInlineableBlock(arg2)); } if (arg3) { post("isAnInlineableBlock arg3 %d\n", isAnInlineableBlock(arg3)); post("arg3->mNext %p\n", arg3->mNext); } DUMPNODE(arg1, 0); */ PyrSlot selector; SetSymbol(&selector, gSpecialSelectors[opmIf]); PyrSlotNode* selectorNode = newPyrSlotNode(&selector); PyrCallNode* callNode = newPyrCallNode(selectorNode, arg1, nullptr, nullptr); // post("<-buildCase %d\n", numArgs); return callNode; } void compileCaseMsg(PyrCallNodeBase2* node) { PyrParseNode* argnode = node->mArglist; bool canInline = true; for (; argnode; argnode = argnode->mNext) { if (!isAnInlineableBlock(argnode)) { canInline = false; break; } } PyrSlot dummy; if (canInline) { PyrCallNode* callNode = buildCase(node->mArglist); callNode->compile(&dummy); } else { int numArgs = 0; argnode = node->mArglist; for (; argnode; argnode = argnode->mNext, ++numArgs) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmCase); } } void compileSwitchMsg(PyrCallNode* node) { PyrSlot dummy; bool canInline = true; int numArgs; { PyrParseNode* argnode = node->mArglist; numArgs = nodeListLength(argnode); if (numArgs <= 2) { error("Missing argument in switch statement"); nodePostErrorLine(node); compileErrors++; }; argnode = argnode->mNext; // skip first arg. PyrParseNode* nextargnode = nullptr; for (; argnode; argnode = nextargnode) { nextargnode = argnode->mNext; if (nextargnode != nullptr) { if (!isAtomicLiteral(argnode) && !isAnInlineableAtomicLiteralBlock(argnode)) { canInline = false; break; } if (!isAnInlineableBlock(nextargnode)) { canInline = false; break; } nextargnode = nextargnode->mNext; } else { if (!isAnInlineableBlock(argnode)) { canInline = false; } break; } } } if (canInline) { PyrParseNode* argnode = node->mArglist; int flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; int arraySize = NEXTPOWEROFTWO(numArgs * 2); PyrObject* array = newPyrArray(compileGC(), arraySize, flags, false); array->size = arraySize; nilSlots(array->slots, arraySize); PyrSlot slot; SetObject(&slot, array); COMPILENODE(argnode, &dummy, false); compilePushConstant(node, &slot); compileByte(143); // lookup slot in dictionary and jump to offset. compileByte(28); argnode = argnode->mNext; // skip first arg. PyrParseNode* nextargnode = nullptr; int absoluteOffset = byteCodeLength(gCompilingByteCodes); int offset = 0; int lastOffset = 0; for (; argnode; argnode = nextargnode) { nextargnode = argnode->mNext; if (nextargnode != nullptr) { ByteCodes byteCodes = compileSubExpressionWithGoto((PyrPushLitNode*)nextargnode, 0x6666, true); PyrSlot* key; PyrSlot value; SetInt(&value, offset); PyrPushLitNode* keyargnode = (PyrPushLitNode*)argnode; if (isAtomicLiteral(argnode)) { key = &keyargnode->mSlot; } else { PyrBlockNode* bnode = (PyrBlockNode*)slotRawPtr(&keyargnode->mSlot); PyrDropNode* dropnode = (PyrDropNode*)bnode->mBody; PyrPushLitNode* litnode = (PyrPushLitNode*)dropnode->mExpr1; key = &litnode->mSlot; } int index = arrayAtIdentityHashInPairs(array, key); PyrSlot* slot = array->slots + index; slotCopy(slot, key); SetInt(slot + 1, offset); if (byteCodes) { offset += byteCodeLength(byteCodes); compileAndFreeByteCodes(byteCodes); } else { compileOpcode(opPushSpecialValue, opsvNil); offset += 1; } nextargnode = nextargnode->mNext; if (nextargnode == nullptr) { compileOpcode(opPushSpecialValue, opsvNil); lastOffset = offset; offset += 1; } } else { ByteCodes byteCodes = compileSubExpressionWithGoto((PyrPushLitNode*)argnode, 0, true); lastOffset = offset; if (byteCodes) { offset += byteCodeLength(byteCodes); compileAndFreeByteCodes(byteCodes); } else { compileOpcode(opPushSpecialValue, opsvNil); lastOffset = offset; offset += 1; } } } Byte* bytes = gCompilingByteCodes->bytes + absoluteOffset; PyrSlot* slots = array->slots; { int jumplen = offset - lastOffset; bytes[lastOffset - 2] = (jumplen >> 8) & 255; bytes[lastOffset - 1] = jumplen & 255; } for (int i = 0; i < arraySize; i += 2) { PyrSlot* key = slots + i; PyrSlot* value = key + 1; if (IsNil(value)) { SetInt(value, lastOffset); } else { int offsetToHere = slotRawInt(value); if (offsetToHere) { int jumplen = offset - offsetToHere; bytes[offsetToHere - 2] = (jumplen >> 8) & 255; bytes[offsetToHere - 1] = jumplen & 255; } } } } else { PyrParseNode* argnode = node->mArglist; for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmSwitch); } } void compileWhileMsg(PyrCallNodeBase2* node) { int numArgs; PyrParseNode* argnode; PyrSlot dummy; ByteCodes whileByteCodes, exprByteCodes; int whileByteCodeLen, exprByteCodeLen; numArgs = nodeListLength(node->mArglist); if (numArgs == 1 && isAnInlineableBlock(node->mArglist)) { whileByteCodes = compileSubExpression((PyrPushLitNode*)node->mArglist, false); whileByteCodeLen = byteCodeLength(whileByteCodes); compileAndFreeByteCodes(whileByteCodes); exprByteCodeLen = 1; compileJump(opcJumpIfFalsePushNil, exprByteCodeLen + 3); // opcJumpBak does a drop.. compileOpcode(opPushSpecialValue, opsvNil); compileJump(opcJumpBak, exprByteCodeLen + whileByteCodeLen + 4); } else if (numArgs == 2 && isWhileTrue(node->mArglist) && isAnInlineableBlock(node->mArglist->mNext)) { exprByteCodes = compileSubExpression((PyrPushLitNode*)node->mArglist->mNext, false); exprByteCodeLen = byteCodeLength(exprByteCodes); compileAndFreeByteCodes(exprByteCodes); compileJump(opcJumpBak, exprByteCodeLen + 1); } else if (numArgs == 2 && isAnInlineableBlock(node->mArglist) && isAnInlineableBlock(node->mArglist->mNext)) { whileByteCodes = compileSubExpression((PyrPushLitNode*)node->mArglist, false); exprByteCodes = compileSubExpression((PyrPushLitNode*)node->mArglist->mNext, false); whileByteCodeLen = byteCodeLength(whileByteCodes); compileAndFreeByteCodes(whileByteCodes); if (exprByteCodes) { exprByteCodeLen = byteCodeLength(exprByteCodes); compileJump(opcJumpIfFalsePushNil, exprByteCodeLen + 3); compileAndFreeByteCodes(exprByteCodes); } else { exprByteCodeLen = 1; compileJump(opcJumpIfFalsePushNil, exprByteCodeLen + 3); // opcJumpBak does a drop.. compileOpcode(opPushSpecialValue, opsvNil); } compileJump(opcJumpBak, exprByteCodeLen + whileByteCodeLen + 4); } else { argnode = node->mArglist; for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmWhile); } } void compileLoopMsg(PyrCallNodeBase2* node) { int numArgs; PyrParseNode* argnode; PyrSlot dummy; ByteCodes exprByteCodes; int exprByteCodeLen; numArgs = nodeListLength(node->mArglist); if (numArgs == 1 && isAnInlineableBlock(node->mArglist)) { exprByteCodes = compileSubExpression((PyrPushLitNode*)node->mArglist, false); exprByteCodeLen = byteCodeLength(exprByteCodes); compileAndFreeByteCodes(exprByteCodes); compileJump(opcJumpBak, exprByteCodeLen + 1); } else { argnode = node->mArglist; for (; argnode; argnode = argnode->mNext) { COMPILENODE(argnode, &dummy, false); } compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(opmLoop); } } PyrBinopCallNode* newPyrBinopCallNode(PyrSlotNode* selector, PyrParseNode* arg1, PyrParseNode* arg2, PyrParseNode* arg3) { PyrBinopCallNode* node = ALLOCNODE(PyrBinopCallNode); node->mSelector = selector; node->mArglist = arg1; arg1->mNext = arg2; arg2->mNext = arg3; return node; } int PyrBinopCallNode::isPartialApplication() { int sum = 0; PyrParseNode* argnode = mArglist; for (; argnode; argnode = argnode->mNext) { if (argnode->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)argnode)->mArgNum = sum; sum++; } } return sum; } void PyrBinopCallNode::compileCall(PyrSlot* result) { int index, selType, isSuper, numArgs; PyrSlot dummy; PyrParseNode* arg1 = mArglist; PyrParseNode* arg2 = arg1->mNext; PyrParseNode* arg3 = arg2->mNext; // postfl("compilePyrBinopCallNode\n"); isSuper = isSuperObjNode(arg1); slotRawSymbol(&mSelector->mSlot)->flags |= sym_Called; index = conjureSelectorIndex((PyrParseNode*)mSelector, gCompilingBlock, isSuper, slotRawSymbol(&mSelector->mSlot), &selType); numArgs = arg3 ? 3 : 2; if (isSuper) { COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); if (arg3) COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSendSuper, numArgs); compileByte(index); } else { switch (selType) { case selNormal: COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); if (arg3) COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSendMsg, numArgs); compileByte(index); break; case selSpecial: COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); if (arg3) COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSendSpecialMsg, numArgs); compileByte(index); break; case selUnary: COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); if (arg3) COMPILENODE(arg3, &dummy, false); compileTail(); if (arg3) compileOpcode(opSpecialOpcode, opcDrop); // drop third argument compileOpcode(opSpecialOpcode, opcDrop); // drop second argument compileOpcode(opSendSpecialUnaryArithMsg, index); break; case selBinary: if (arg3) { COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSpecialOpcode, opcSpecialBinaryOpWithAdverb); compileByte(index); } else if (index == opAdd && arg2->mClassno == pn_PushLitNode && IsInt(&((PyrPushLitNode*)arg2)->mSlot) && slotRawInt(&((PyrPushLitNode*)arg2)->mSlot) == 1) { COMPILENODE(arg1, &dummy, false); compileOpcode(opPushSpecialValue, opsvPlusOne); } else if (index == opSub && arg2->mClassno == pn_PushLitNode && IsInt(&((PyrPushLitNode*)arg2)->mSlot) && slotRawInt(&((PyrPushLitNode*)arg2)->mSlot) == 1) { COMPILENODE(arg1, &dummy, false); compileTail(); compileOpcode(opPushSpecialValue, opsvMinusOne); } else { COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); compileTail(); compileOpcode(opSendSpecialBinaryArithMsg, index); } break; case selIf: compileAnyIfMsg(this); break; case selCase: compileCaseMsg(this); break; case selWhile: compileWhileMsg(this); break; case selLoop: compileLoopMsg(this); break; case selAnd: compileAndMsg(arg1, arg2); break; case selOr: compileOrMsg(arg1, arg2); break; case selQuestionMark: compileQMsg(arg1, arg2); break; case selDoubleQuestionMark: compileQQMsg(arg1, arg2); break; case selExclamationQuestionMark: compileXQMsg(arg1, arg2); break; default: COMPILENODE(arg1, &dummy, false); COMPILENODE(arg2, &dummy, false); if (arg3) COMPILENODE(arg3, &dummy, false); compileTail(); compileOpcode(opSendMsg, numArgs); compileByte(index); break; } } } PyrPushKeyArgNode* newPyrPushKeyArgNode(PyrSlotNode* selector, PyrParseNode* expr) { PyrPushKeyArgNode* node = ALLOCNODE(PyrPushKeyArgNode); node->mSelector = selector; node->mExpr = expr; return node; } void PyrPushKeyArgNode::compile(PyrSlot* result) { PyrSlot dummy; // postfl("->compilePyrPushKeyArgNode\n"); compilePushConstant((PyrParseNode*)this, &mSelector->mSlot); COMPILENODE(mExpr, &dummy, false); } PyrDropNode* newPyrDropNode(PyrParseNode* expr1, PyrParseNode* expr2) { PyrDropNode* node = ALLOCNODE(PyrDropNode); node->mExpr1 = expr1; node->mExpr2 = expr2; return node; } void PyrDropNode::compile(PyrSlot* result) { // postfl("->compilePyrDropNode\n"); PyrSlot dummy; // eliminate as many drops as possible if (!mExpr2) { post("DROP EXPR2 NULL\n"); COMPILENODE(mExpr1, &dummy, true); } else if (mExpr2->mClassno == pn_BlockReturnNode) { // no drop before a block return COMPILENODE(mExpr1, &dummy, true); } else if (mExpr1 && mExpr1->mClassno == pn_AssignNode) { // let the store do the drop ((PyrAssignNode*)mExpr1)->mDrop = 1; COMPILENODE(mExpr1, &dummy, false); COMPILENODE(mExpr2, &dummy, true); } else if (mExpr1 && mExpr1->mClassno == pn_DropNode) { PyrDropNode* znode; // let the store do the drop, a bit more complex. // find the ultimate expression in the left subtree before the drop. znode = (PyrDropNode*)mExpr1; while (znode->mExpr2 && znode->mExpr2->mClassno == pn_DropNode) { znode = (PyrDropNode*)znode->mExpr2; } if (znode->mExpr2->mClassno == pn_AssignNode) { ((PyrAssignNode*)znode->mExpr2)->mDrop = 1; COMPILENODE(mExpr1, &dummy, false); COMPILENODE(mExpr2, &dummy, true); } else { COMPILENODE(mExpr1, &dummy, false); compileOpcode(opSpecialOpcode, opcDrop); COMPILENODE(mExpr2, &dummy, true); } } else { COMPILENODE(mExpr1, &dummy, false); compileOpcode(opSpecialOpcode, opcDrop); COMPILENODE(mExpr2, &dummy, true); } // postfl("<-compilePyrDropNode\n"); } PyrPushLitNode* newPyrPushLitNode(PyrSlotNode* literalSlot, PyrParseNode* literalObj) { PyrPushLitNode* node; if (literalSlot) { node = literalSlot; node->mClassno = pn_PushLitNode; } else { node = ALLOCSLOTNODE(PyrSlotNode, pn_PushLitNode); SetPtr(&node->mSlot, (PyrObject*)literalObj); } return node; } void compilePushConstant(PyrParseNode* node, PyrSlot* slot) { int index = conjureConstantIndex(node, gCompilingBlock, slot); if (index < (1 << 4)) { compileByte((opPushLiteral << 4) | index); } else if (index < (1 << 8)) { compileByte(40); compileByte(index & 0xFF); } else if (index < (1 << 16)) { compileByte(41); compileByte((index >> 8) & 0xFF); compileByte(index & 0xFF); } else if (index < (1 << 24)) { compileByte(42); compileByte((index >> 16) & 0xFF); compileByte((index >> 8) & 0xFF); compileByte(index & 0xFF); } else { compileByte(43); compileByte((index >> 24) & 0xFF); compileByte((index >> 16) & 0xFF); compileByte((index >> 8) & 0xFF); compileByte(index & 0xFF); } } void compilePushInt(int value) { // postfl("compilePushInt\n"); if (value >= -1 && value <= 2) { compileOpcode(opPushSpecialValue, opsvZero + value); } else { // printf("int %d\n", value); if (value >= -(1 << 7) && value <= ((1 << 7) - 1)) { compileByte(44); compileByte(value & 0xFF); } else if (value >= -(1 << 15) && value <= ((1 << 15) - 1)) { compileByte(45); compileByte((value >> 8) & 0xFF); compileByte(value & 0xFF); } else if (value >= -(1 << 23) && value <= ((1 << 23) - 1)) { compileByte(46); compileByte((value >> 16) & 0xFF); compileByte((value >> 8) & 0xFF); compileByte(value & 0xFF); } else { compileByte(47); compileByte((value >> 24) & 0xFF); compileByte((value >> 16) & 0xFF); compileByte((value >> 8) & 0xFF); compileByte(value & 0xFF); } } } void PyrSlotNode::compilePushLit(PyrSlot* result) { int index; PyrSlot slot; ByteCodes savedBytes; // postfl("compilePyrPushLitNode\n"); if (IsPtr(&mSlot)) { PyrParseNode* literalObj = (PyrParseNode*)slotRawPtr(&mSlot); // index = conjureLiteralObjIndex(gCompilingBlock, literalObj); if (literalObj->mClassno == pn_BlockNode) { savedBytes = saveByteCodeArray(); COMPILENODE(literalObj, &slot, false); restoreByteCodeArray(savedBytes); index = conjureLiteralSlotIndex(literalObj, gCompilingBlock, &slot); compileOpcode(opExtended, opPushLiteral); compileByte(index); PyrBlock* block = slotRawBlock(&slot); if (NotNil(&block->contextDef)) { METHRAW(gCompilingBlock)->needsHeapContext = 1; } } else { COMPILENODE(literalObj, &slot, false); compilePushConstant((PyrParseNode*)literalObj, &slot); } } else { slot = mSlot; if (IsInt(&slot)) { compilePushInt(slotRawInt(&slot)); } else if (SlotEq(&slot, &o_nil)) { compileOpcode(opPushSpecialValue, opsvNil); } else if (SlotEq(&slot, &o_true)) { compileOpcode(opPushSpecialValue, opsvTrue); } else if (SlotEq(&slot, &o_false)) { compileOpcode(opPushSpecialValue, opsvFalse); } else if (SlotEq(&slot, &o_fhalf)) { compileOpcode(opPushSpecialValue, opsvFHalf); } else if (SlotEq(&slot, &o_fnegone)) { compileOpcode(opPushSpecialValue, opsvFNegOne); } else if (SlotEq(&slot, &o_fzero)) { compileOpcode(opPushSpecialValue, opsvFZero); } else if (SlotEq(&slot, &o_fone)) { compileOpcode(opPushSpecialValue, opsvFOne); } else if (SlotEq(&slot, &o_ftwo)) { compileOpcode(opPushSpecialValue, opsvFTwo); } else if (SlotEq(&slot, &o_inf)) { compileOpcode(opPushSpecialValue, opsvInf); } else if (IsFloat(&slot)) { compilePushConstant((PyrParseNode*)this, &slot); } else if (IsSym(&slot)) { compilePushConstant((PyrParseNode*)this, &slot); } else { compilePushConstant((PyrParseNode*)this, &slot); } } } PyrLiteralNode* newPyrLiteralNode(PyrSlotNode* literalSlot, PyrParseNode* literalObj) { PyrLiteralNode* node; if (literalSlot) { node = literalSlot; node->mClassno = pn_LiteralNode; } else { node = ALLOCSLOTNODE(PyrSlotNode, pn_LiteralNode); SetPtr(&node->mSlot, (PyrObject*)literalObj); } return node; } void compilePyrLiteralNode(PyrLiteralNode* node, PyrSlot* result) { if (!node) { SetNil(result); } else { node->compileLiteral(result); } } void PyrSlotNode::compileLiteral(PyrSlot* result) { ByteCodes savedBytes; if (IsPtr(&mSlot)) { PyrParseNode* literalObj = (PyrParseNode*)slotRawPtr(&mSlot); if (literalObj->mClassno == pn_BlockNode) { savedBytes = saveByteCodeArray(); COMPILENODE(literalObj, result, false); restoreByteCodeArray(savedBytes); PyrBlock* block = slotRawBlock(result); if (NotNil(&block->contextDef)) { METHRAW(gCompilingBlock)->needsHeapContext = 1; } } else { COMPILENODE(literalObj, result, false); } } else { *(PyrSlot*)result = mSlot; } } PyrReturnNode* newPyrReturnNode(PyrParseNode* expr) { PyrReturnNode* node = ALLOCNODE(PyrReturnNode); node->mExpr = expr; return node; } void PyrReturnNode::compile(PyrSlot* result) { PyrPushLitNode* lit; PyrSlot dummy; // post("->compilePyrReturnNode\n"); gFunctionCantBeClosed = true; if (!mExpr) { compileOpcode(opSpecialOpcode, opcReturnSelf); } else if (mExpr->mClassno == pn_PushLitNode) { lit = (PyrPushLitNode*)mExpr; if (IsSym(&(lit->mSlot)) && slotRawSymbol(&lit->mSlot) == s_this) { compileOpcode(opSpecialOpcode, opcReturnSelf); } else if (IsNil(&lit->mSlot)) { compileOpcode(opSpecialOpcode, opcReturnNil); } else if (IsTrue(&lit->mSlot)) { compileOpcode(opSpecialOpcode, opcReturnTrue); } else if (IsFalse(&lit->mSlot)) { compileOpcode(opSpecialOpcode, opcReturnFalse); } else { COMPILENODE(lit, &dummy, false); compileOpcode(opSpecialOpcode, opcReturn); } } else { SetTailBranch branch(true); SetTailIsMethodReturn mr(true); COMPILENODE(mExpr, &dummy, true); compileOpcode(opSpecialOpcode, opcReturn); } // post("<-compilePyrReturnNode\n"); } PyrBlockReturnNode* newPyrBlockReturnNode() { PyrBlockReturnNode* node = ALLOCNODE(PyrBlockReturnNode); return node; } void PyrBlockReturnNode::compile(PyrSlot* result) { // postfl("compilePyrBlockReturnNode\n"); // compileOpcode(opSpecialOpcode, opcFunctionReturn); } PyrAssignNode* newPyrAssignNode(PyrSlotNode* varName, PyrParseNode* expr, int flags) { PyrAssignNode* node = ALLOCNODE(PyrAssignNode); node->mVarName = varName; node->mExpr = expr; node->mDrop = 0; return node; } PyrSetterNode* newPyrSetterNode(PyrSlotNode* selector, PyrParseNode* expr1, PyrParseNode* expr2) { PyrSetterNode* node = ALLOCNODE(PyrSetterNode); node->mSelector = selector; node->mExpr1 = expr1; node->mExpr2 = expr2; return node; } PyrMultiAssignNode* newPyrMultiAssignNode(PyrMultiAssignVarListNode* varList, PyrParseNode* expr, int flags) { PyrMultiAssignNode* node = ALLOCNODE(PyrMultiAssignNode); node->mVarList = varList; node->mExpr = expr; node->mDrop = 0; return node; } PyrMultiAssignVarListNode* newPyrMultiAssignVarListNode(PyrSlotNode* varNames, PyrSlotNode* rest) { PyrMultiAssignVarListNode* node = ALLOCNODE(PyrMultiAssignVarListNode); node->mVarNames = varNames; node->mRest = rest; return node; } void compileAssignVar(PyrParseNode* node, PyrSymbol* varName, bool drop) { int level, index, vindex, varType; PyrBlock* tempfunc; PyrClass* classobj; // postfl("compileAssignVar\n"); classobj = gCompilingClass; if (varName == s_this || varName == s_super || varName == s_curProcess || varName == s_curThread || varName == s_curMethod || varName == s_curBlock || varName == s_curClosure) { error("You may not assign to '%s'.", varName->name); nodePostErrorLine(node); compileErrors++; } else if (varName->name[0] >= 'A' && varName->name[0] <= 'Z') { // actually this shouldn't even parse, so you won't get here. error("You may not assign to a class name."); nodePostErrorLine(node); compileErrors++; } else if (findVarName(gCompilingBlock, &classobj, varName, &varType, &level, &index, &tempfunc)) { switch (varType) { case varInst: if (drop) { if (index <= 15) { compileByte((opStoreInstVar << 4) | index); } else { compileByte(opStoreInstVar); compileByte(index); compileByte((opSpecialOpcode << 4) | opcDrop); } } else { compileByte(opStoreInstVar); compileByte(index); } break; case varClass: { index += slotRawInt(&classobj->classVarIndex); if (drop) { if (index < 4096) { compileByte((opStoreClassVar << 4) | ((index >> 8) & 15)); compileByte(index & 255); } else { compileByte(opStoreClassVar); assert(false); vindex = 0; compileByte(vindex); // FIXME: vindex is not initalized!!!! compileByte(index); compileByte((opSpecialOpcode << 4) | opcDrop); } } else { compileByte(opStoreClassVar); compileByte((index >> 8) & 255); compileByte(index & 255); } } break; case varConst: { error("You may not assign to a constant."); nodePostErrorLine(node); compileErrors++; } break; case varTemp: // compileOpcode(opStoreTempVar, level); // compileByte(index); if (drop) { if (index <= 15 && level < 8) { compileByte((opStoreTempVar << 4) | level); compileByte(index); } else { compileByte(opStoreTempVar); compileByte(level); compileByte(index); compileByte((opSpecialOpcode << 4) | opcDrop); } } else { compileByte(opStoreTempVar); compileByte(level); compileByte(index); } break; } } else { error("Variable '%s' not defined.\n", varName->name); nodePostErrorLine(node); compileErrors++; // Debugger(); } } void PyrAssignNode::compile(PyrSlot* result) { PyrSlot dummy; // postfl("compilePyrAssignNode\n"); COMPILENODE(mExpr, &dummy, false); compileAssignVar((PyrParseNode*)this, slotRawSymbol(&mVarName->mSlot), mDrop); } int PyrSetterNode::isPartialApplication() { int sum = 0; if (mExpr1->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)mExpr1)->mArgNum = sum; sum++; } if (mExpr2->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)mExpr2)->mArgNum = sum; sum++; } return sum; } void PyrSetterNode::compileCall(PyrSlot* result) { int index, selType, isSuper; PyrSlot dummy; char setterName[128]; PyrSymbol* setterSym; // postfl("compilePyrSetterNode\n"); if (nodeListLength(mExpr1) > 1) { error("Setter method called with too many arguments.\n"); nodePostErrorLine(mExpr1); compileErrors++; } else { COMPILENODE(mExpr1, &dummy, false); COMPILENODE(mExpr2, &dummy, false); // postfl("compilePyrCallNode\n"); isSuper = isSuperObjNode(mExpr1); sprintf(setterName, "%s_", slotRawSymbol(&mSelector->mSlot)->name); setterSym = getsym(setterName); slotRawSymbol(&mSelector->mSlot)->flags |= sym_Called; index = conjureSelectorIndex((PyrParseNode*)mSelector, gCompilingBlock, isSuper, setterSym, &selType); if (isSuper) { compileTail(); compileOpcode(opSendSuper, 2); compileByte(index); } else { compileTail(); compileOpcode(opSendMsg, 2); compileByte(index); } } } void PyrMultiAssignNode::compile(PyrSlot* result) { PyrSlot dummy; // postfl("compilePyrMultiAssignNode\n"); COMPILENODE(mExpr, &dummy, false); COMPILENODE(mVarList, &dummy, false); } void PyrMultiAssignVarListNode::compile(PyrSlot* result) { int i, numAssigns; PyrSlotNode* varname; // postfl("compilePyrMultiAssignVarListNode\n"); numAssigns = nodeListLength((PyrParseNode*)mVarNames); varname = mVarNames; for (i = 0; i < numAssigns; ++i, varname = (PyrSlotNode*)varname->mNext) { compileOpcode(opSpecialOpcode, opcDup); compilePushInt(i); compileOpcode(opSendSpecialMsg, 2); compileByte(opmAt); compileAssignVar((PyrParseNode*)varname, slotRawSymbol(&varname->mSlot), 1); // compileOpcode(opSpecialOpcode, opcDrop); } if (mRest) { compileOpcode(opSpecialOpcode, opcDup); compilePushInt(i); compileOpcode(opSendSpecialMsg, 2); compileByte(opmCopyToEnd); compileAssignVar((PyrParseNode*)mRest, slotRawSymbol(&mRest->mSlot), 1); // compileOpcode(opSpecialOpcode, opcDrop); } } PyrDynDictNode* newPyrDynDictNode(PyrParseNode* elems) { PyrDynDictNode* node; // if (compilingCmdLine) post("newPyrDynDictNode\n"); node = ALLOCNODE(PyrDynDictNode); node->mElems = elems; return node; } int PyrDynDictNode::isPartialApplication() { int sum = 0; int numItems = nodeListLength(mElems); PyrParseNode* inode = mElems; for (int i = 0; i < numItems; ++i) { if (inode->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)inode)->mArgNum = sum; sum++; } inode = (PyrParseNode*)inode->mNext; } return sum; } void PyrDynDictNode::compileCall(PyrSlot* result) { int i, numItems; PyrParseNode* inode; PyrSlot dummy; // postfl("compilePyrDynDictNode\n"); numItems = nodeListLength(mElems) >> 1; compilePushVar((PyrParseNode*)this, s_event); compilePushInt(numItems); compileByte(110); // push nil for proto compileByte(110); // push nil for parent compileByte(108); // push true for know compileOpcode(opSendSpecialMsg, 5); compileByte(opmNew); inode = mElems; for (i = 0; i < numItems; ++i) { // if (compilingCmdLine) post("+ %d %d\n", i, gCompilingByteCodes->size); COMPILENODE(inode, &dummy, false); inode = (PyrParseNode*)inode->mNext; COMPILENODE(inode, &dummy, false); inode = (PyrParseNode*)inode->mNext; compileOpcode(opSendSpecialMsg, 3); compileByte(opmPut); } } PyrDynListNode* newPyrDynListNode(PyrParseNode* classname, PyrParseNode* elems) { PyrDynListNode* node; // if (compilingCmdLine) post("newPyrDynListNode\n"); node = ALLOCNODE(PyrDynListNode); node->mClassname = classname; node->mElems = elems; return node; } int PyrDynListNode::isPartialApplication() { int sum = 0; int numItems = nodeListLength(mElems); PyrParseNode* inode = mElems; for (int i = 0; i < numItems; ++i) { if (inode->mClassno == pn_CurryArgNode) { ((PyrCurryArgNode*)inode)->mArgNum = sum; sum++; } inode = (PyrParseNode*)inode->mNext; } return sum; } void PyrDynListNode::compileCall(PyrSlot* result) { int i, numItems; PyrParseNode* inode; PyrSlot dummy; // postfl("compilePyrDynListNode\n"); numItems = nodeListLength(mElems); if (mClassname) { compilePushVar((PyrParseNode*)this, slotRawSymbol(&((PyrSlotNode*)mClassname)->mSlot)); } else { compilePushVar((PyrParseNode*)this, s_array); } // compileOpcode(opExtended, opPushSpecialValue); // compileByte(op_class_list); compilePushInt(numItems); compileOpcode(opSendSpecialMsg, 2); compileByte(opmNew); inode = mElems; for (i = 0; i < numItems; ++i, inode = (PyrParseNode*)inode->mNext) { // if (compilingCmdLine) post("+ %d %d\n", i, gCompilingByteCodes->size); COMPILENODE(inode, &dummy, false); compileOpcode(opSendSpecialMsg, 2); compileByte(opmAdd); } } PyrLitListNode* newPyrLitListNode(PyrParseNode* classname, PyrParseNode* elems) { PyrLitListNode* node = ALLOCNODE(PyrLitListNode); node->mClassname = classname; node->mElems = elems; return node; } void PyrLitListNode::compile(PyrSlot* result) { PyrSlot* resultSlot; PyrSlot itemSlot; PyrObject* array; PyrParseNode* inode; int i, numItems, flags; // postfl("->compilePyrLitListNode\n"); if (mClassname && slotRawSymbol(&((PyrSlotNode*)mClassname)->mSlot) != s_array) { error("Only Array is supported as literal type.\n"); post("Compiling as an Array.\n"); } resultSlot = (PyrSlot*)result; numItems = mElems ? nodeListLength(mElems) : 0; flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; array = newPyrArray(compileGC(), numItems, flags, false); inode = mElems; for (i = 0; i < numItems; ++i, inode = (PyrParseNode*)inode->mNext) { COMPILENODE(inode, &itemSlot, false); array->slots[i] = itemSlot; } array->size = numItems; SetObject(resultSlot, array); // postfl("<-compilePyrLitListNode\n"); } PyrLitDictNode* newPyrLitDictNode(PyrParseNode* elems) { PyrLitDictNode* node = ALLOCNODE(PyrLitDictNode); node->mElems = elems; return node; } int litDictPut(PyrObject* dict, PyrSlot* key, PyrSlot* value); int litDictPut(PyrObject* dict, PyrSlot* key, PyrSlot* value) { #if 0 PyrSlot *slot, *newslot; int i, index, size; PyrObject *array; bool knows = IsTrue(dict->slots + ivxIdentDict_know); if (knows && IsSym(key)) { if (slotRawSymbol(key) == s_parent) { slotCopy(&dict->slots[ivxIdentDict_parent], value); return errNone; } if (slotRawSymbol(key) == s_proto) { slotCopy(&dict->slots[ivxIdentDict_proto], value); return errNone; } } array = slotRawObject(&dict->slots[ivxIdentDict_array]); if (!isKindOf((PyrObject*)array, class_array)) return errFailed; index = arrayAtIdentityHashInPairs(array, key); slot = array->slots + index; slotCopy(&slot[1], value); if (IsNil(slot)) { slotCopy(slot, key); } #endif return errNone; } void PyrLitDictNode::dump(int level) {} void PyrLitDictNode::compile(PyrSlot* result) { #if 0 PyrSlot *resultSlot; PyrSlot itemSlot; PyrObject *array; PyrParseNode *inode; int i, numItems, flags; //postfl("->compilePyrLitDictNode\n"); if (mClassname && slotRawSymbol(&((PyrSlotNode*)mClassname)->mSlot) != s_array) { error("Only Array is supported as literal type.\n"); post("Compiling as an Array.\n"); } resultSlot = (PyrSlot*)result; numItems = mElems ? nodeListLength(mElems) : 0; int numSlots = NEXTPOWEROFTWO(numItems*2); PyrObject *obj = instantiateObject(g->gc, class_event->u.classobj, 0, true, false); PyrSlot *slots = obj->slots; flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; array = newPyrArray(compileGC(), numSlots, flags, false); nilSlots(array->slots, numSlots); inode = mElems; for (i=0; i<numItems; ++i, inode = (PyrParseNode*)inode->mNext) { COMPILENODE(inode, &itemSlot, false); array->slots[i] = itemSlot; } array->size = numItems; SetObject(resultSlot, array); //postfl("<-compilePyrLitListNode\n"); #endif } extern LongStack closedFuncCharNo; extern int lastClosedFuncCharNo; PyrBlockNode* newPyrBlockNode(PyrArgListNode* arglist, PyrVarListNode* varlist, PyrParseNode* body, bool isTopLevel) { PyrBlockNode* node = ALLOCNODE(PyrBlockNode); node->mArglist = arglist; catVarLists(varlist); node->mVarlist = varlist; node->mBody = body; node->mIsTopLevel = isTopLevel; node->mBeginCharNo = lastClosedFuncCharNo; return node; } void PyrBlockNode::compile(PyrSlot* slotResult) { PyrBlock *block, *prevBlock; PyrMethodRaw* methraw; int i, j, numArgs, numVars; int numVariableArgs = 0; int numKwArgs = 0; int numSlots, numArgNames, flags; PyrVarDefNode* vardef; PyrObject* proto; PyrSymbolArray *argNames, *varNames; PyrSlot dummy; bool hasVarExprs = false; // postfl("->block\n"); // create a new block object flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; block = newPyrBlock(flags); SetObject(slotResult, block); int prevFunctionHighestExternalRef = gFunctionHighestExternalRef; bool prevFunctionCantBeClosed = gFunctionCantBeClosed; gFunctionHighestExternalRef = 0; gFunctionCantBeClosed = false; prevBlock = gCompilingBlock; PyrClass* prevClass = gCompilingClass; gCompilingBlock = block; PyrBlock* prevPartiallyAppliedFunction = gPartiallyAppliedFunction; gPartiallyAppliedFunction = nullptr; methraw = METHRAW(block); methraw->unused1 = 0; methraw->unused2 = 0; int endCharNo = linestarts[mLineno] + mCharno; int stringLength = endCharNo - mBeginCharNo; int lastChar = text[mBeginCharNo + stringLength - 1]; if (lastChar == 0) stringLength--; methraw->needsHeapContext = 0; if (mIsTopLevel) { gCompilingClass = class_interpreter; SetNil(&block->contextDef); } else { SetObject(&block->contextDef, prevBlock); } methraw->varargs = 0; if (mArglist) { if (mArglist->mRest) { methraw->varargs += 1; numVariableArgs = 1; if (mArglist->mKeywordArgs) { methraw->varargs += 1; numKwArgs = 1; } } } numArgs = mArglist ? nodeListLength((PyrParseNode*)mArglist->mVarDefs) : 0; numVars = mVarlist ? nodeListLength((PyrParseNode*)mVarlist->mVarDefs) : 0; if (numArgs > 255) { error("Too many arguments in function definition (> 255)\n"); nodePostErrorLine((PyrParseNode*)mArglist->mVarDefs); compileErrors++; } numSlots = numArgs + numVariableArgs + numKwArgs + numVars; methraw->frameSize = (numSlots + FRAMESIZE) * sizeof(PyrSlot); if (numSlots) { proto = newPyrArray(compileGC(), numSlots, flags, false); proto->size = numSlots; SetObject(&block->prototypeFrame, proto); } else { SetNil(&block->prototypeFrame); } methraw->numargs = numArgs; methraw->numvars = numVars; methraw->posargs = numArgs + numVariableArgs + numKwArgs; methraw->numtemps = numSlots; methraw->popSize = numSlots; numArgNames = methraw->posargs; if (numArgNames) { argNames = newPyrSymbolArray(compileGC(), numArgNames, flags, false); argNames->size = numArgNames; SetObject(&block->argNames, argNames); } else { SetNil(&block->argNames); } if (numVars) { varNames = newPyrSymbolArray(compileGC(), numVars, flags, false); varNames->size = numVars; SetObject(&block->varNames, varNames); } else { SetNil(&block->varNames); } // declare args if (numArgs) { PyrSymbol** blockargs; blockargs = slotRawSymbolArray(&block->argNames)->symbols; vardef = mArglist->mVarDefs; for (i = 0; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot* varslot; varslot = &vardef->mVarName->mSlot; // already declared as arg? for (j = 0; j < i; ++j) { if (blockargs[j] == slotRawSymbol(varslot)) { error("Function argument '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in mArglist blockargs[i] = slotRawSymbol(varslot); // postfl("defarg %d '%s'\n", i, slotRawSymbol(slot)->name); } } if (numVariableArgs > 0) { PyrSlot* varslot; PyrSymbol** blockargs; blockargs = slotRawSymbolArray(&block->argNames)->symbols; varslot = &mArglist->mRest->mSlot; // already declared as arg? for (j = 0; j < numArgs; ++j) { if (blockargs[j] == slotRawSymbol(varslot)) { error("Function argument '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in mArglist blockargs[numArgs] = slotRawSymbol(varslot); // postfl("defrest '%s'\n", slotRawSymbol(slot)->name); if (numKwArgs > 0) { PyrSlot* kwvarslot; kwvarslot = &mArglist->mKeywordArgs->mSlot; // already declared as arg? // Add one here to numArgs to include the name of the variableArgument slot for (j = 0; j < numArgs + 1; ++j) { if (blockargs[j] == slotRawSymbol(kwvarslot)) { error("Argument '%s' already declared in %s:%s\n", slotRawSymbol(kwvarslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)kwvarslot); compileErrors++; } } blockargs[numArgs + 1] = slotRawSymbol(kwvarslot); } } // declare vars if (numVars) { PyrSymbol **blockargs, **blockvars; blockargs = slotRawSymbolArray(&block->argNames)->symbols; blockvars = slotRawSymbolArray(&block->varNames)->symbols; vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot* varslot; varslot = &vardef->mVarName->mSlot; // already declared as arg? for (j = 0; j < numArgNames; ++j) { if (blockargs[j] == slotRawSymbol(varslot)) { error("Function variable '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // already declared as var? for (j = 0; j < i; ++j) { if (blockvars[j] == slotRawSymbol(varslot)) { error("Function variable '%s' already declared in %s:%s\n", slotRawSymbol(varslot)->name, slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); nodePostErrorLine((PyrParseNode*)vardef); compileErrors++; } } // put it in varlist blockvars[i] = slotRawSymbol(varslot); // postfl("defvar %d '%s'\n", i, slotRawSymbol(slot)->name); } } if (numArgs) { vardef = mArglist->mVarDefs; for (i = 0; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot *slot, litval; slot = slotRawObject(&block->prototypeFrame)->slots + i; if (vardef->hasExpr(&litval)) hasVarExprs = true; // compilePyrLiteralNode((PyrLiteralNode*)vardef->mDefVal, &litval); *slot = litval; } } if (numVariableArgs > 0) { // SetNil(&slotRawObject(&block->prototypeFrame)->slots[numArgs]); slotCopy(&slotRawObject(&block->prototypeFrame)->slots[numArgs], &o_emptyarray); if (numKwArgs > 0) { slotCopy(&slotRawObject(&block->prototypeFrame)->slots[numArgs + 1], &o_emptyarray); } } if (numVars) { vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { PyrSlot *slot, litval; slot = slotRawObject(&block->prototypeFrame)->slots + i + numArgs + numVariableArgs; if (vardef->hasExpr(&litval)) hasVarExprs = true; // compilePyrLiteralNode(vardef->mDefVal, &litval); *slot = litval; } } methraw->methType = methBlock; // compile body initByteCodes(); { SetTailBranch branch(true); /*if (compilingCmdLine) { post("block %d\n", gIsTailCodeBranch); DUMPNODE(mBody, 0); }*/ SetTailIsMethodReturn mr(false); if (hasVarExprs) { if (mArglist) { vardef = mArglist->mVarDefs; for (i = 0; i < numArgs; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { vardef->compileArg(&dummy); } } if (mVarlist) { vardef = mVarlist->mVarDefs; for (i = 0; i < numVars; ++i, vardef = (PyrVarDefNode*)vardef->mNext) { vardef->compile(&dummy); } } } if (mBody->mClassno == pn_BlockReturnNode) { compileOpcode(opPushSpecialValue, opsvNil); } else { COMPILENODE(mBody, &dummy, true); } } compileOpcode(opSpecialOpcode, opcFunctionReturn); installByteCodes(block); if ((!gFunctionCantBeClosed && gFunctionHighestExternalRef == 0) || mIsTopLevel) { SetNil(&block->contextDef); PyrString* string = newPyrStringN(compileGC(), stringLength, flags, false); memcpy(string->s, text + mBeginCharNo, stringLength); SetObject(&block->sourceCode, string); // static int totalLength = 0, totalStrings = 0; // totalLength += stringLength; // totalStrings++; // post("cf %4d %4d %6d %s:%s \n", totalStrings, stringLength, totalLength, // slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); } gCompilingBlock = prevBlock; gCompilingClass = prevClass; gPartiallyAppliedFunction = prevPartiallyAppliedFunction; gFunctionCantBeClosed = gFunctionCantBeClosed || prevFunctionCantBeClosed; gFunctionHighestExternalRef = sc_max(gFunctionHighestExternalRef - 1, prevFunctionHighestExternalRef); } PyrParseNode* linkNextNode(PyrParseNode* a, PyrParseNode* b) { if (a == nullptr) return b; if (b) { a->mTail->mNext = b; a->mTail = b->mTail; } return a; } PyrParseNode* linkAfterHead(PyrParseNode* a, PyrParseNode* b) { b->mNext = a->mNext; if (!a->mNext) a->mTail = b; a->mNext = b; return a; } bool isSuperObjNode(PyrParseNode* node) { return node->mClassno == pn_PushNameNode && slotRawSymbol(&((PyrPushNameNode*)node)->mSlot) == s_super; } bool isThisObjNode(PyrParseNode* node) { return node->mClassno == pn_PushNameNode && slotRawSymbol(&((PyrPushNameNode*)node)->mSlot) == s_this; } int nodeListLength(PyrParseNode* node) { int length = 0; for (; node; node = node->mNext) length++; return length; } int conjureSelectorIndex(PyrParseNode* node, PyrBlock* func, bool isSuper, PyrSymbol* selector, int* selType) { int i; PyrObject* selectors; PyrSlot* slot; int newsize, flags; flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; if (!isSuper) { if (selector == gSpecialSelectors[opmIf]) { *selType = selIf; return opmIf; } else if (selector == gSpecialSelectors[opmWhile]) { *selType = selWhile; return opmWhile; } else if (selector == gSpecialSelectors[opmAnd]) { *selType = selAnd; return opmAnd; } else if (selector == gSpecialSelectors[opmOr]) { *selType = selOr; return opmOr; } else if (selector == gSpecialSelectors[opmCase]) { *selType = selCase; return opmCase; } else if (selector == gSpecialSelectors[opmSwitch]) { *selType = selSwitch; return opmSwitch; } else if (selector == gSpecialSelectors[opmLoop]) { *selType = selLoop; return opmLoop; } else if (selector == gSpecialSelectors[opmQuestionMark]) { *selType = selQuestionMark; return opmAnd; } else if (selector == gSpecialSelectors[opmDoubleQuestionMark]) { *selType = selDoubleQuestionMark; return opmAnd; } else if (selector == gSpecialSelectors[opmExclamationQuestionMark]) { *selType = selExclamationQuestionMark; return opmAnd; } for (i = 0; i < opmNumSpecialSelectors; ++i) { if (selector == gSpecialSelectors[i]) { *selType = selSpecial; return i; } } for (i = 0; i < opNumUnarySelectors; ++i) { if (selector == gSpecialUnarySelectors[i]) { *selType = selUnary; return i; } } for (i = 0; i < opNumBinarySelectors; ++i) { if (selector == gSpecialBinarySelectors[i]) { *selType = selBinary; return i; } } } if (NotNil(&func->selectors)) { selectors = slotRawObject(&func->selectors); for (i = 0; i < selectors->size; ++i) { if (IsSym(&selectors->slots[i]) && slotRawSymbol(&selectors->slots[i]) == selector) { *selType = selNormal; return i; } } } else { selectors = (PyrObject*)newPyrArray(compileGC(), 2, flags, false); SetObject(&func->selectors, selectors); } // otherwise add it to the selectors table if (selectors->size + 1 >= 256) { error("Selector table too big: too many classes, method selectors or function definitions in this function. " "Simplify the function.\n"); post("Next selector was: %s\n", selector->name); nodePostErrorLine(node); compileErrors++; return 0; } if (selectors->size + 1 > ARRAYMAXINDEXSIZE(selectors)) { // resize literal table newsize = ARRAYMAXINDEXSIZE(selectors) * 2; SetRaw(&func->selectors, (PyrObject*)newPyrArray(compileGC(), newsize, flags, false)); memcpy(slotRawObject(&func->selectors)->slots, selectors->slots, selectors->size * sizeof(PyrSlot)); slotRawObject(&func->selectors)->size = selectors->size; freePyrObject(selectors); selectors = slotRawObject(&func->selectors); } slot = selectors->slots + selectors->size++; SetSymbol(slot, selector); *selType = selNormal; return selectors->size - 1; } int conjureLiteralSlotIndex(PyrParseNode* node, PyrBlock* func, PyrSlot* slot) { int i; PyrObject* selectors; PyrSlot* slot2; int newsize, flags; flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; // lookup slot in selectors table if (IsObj(&func->selectors)) { selectors = slotRawObject(&func->selectors); /*if (selectors->classptr != class_array) { post("compiling %s:%s\n", slotRawSymbol(&gCompilingClass->name)->name, slotRawSymbol(&gCompilingMethod->name)->name); post("selectors is a '%s'\n", selectors->classptr->name.us->name); dumpObjectSlot(slot); Debugger(); }*/ for (i = 0; i < selectors->size; ++i) if (SlotEq(&selectors->slots[i], slot)) return i; } else { selectors = (PyrObject*)newPyrArray(compileGC(), 4, flags, false); SetObject(&func->selectors, selectors); } // otherwise add it to the selectors table if (selectors->size + 1 >= 256) { error("Selector table too big: too many classes, method selectors or function definitions in this function. " "Simplify the function.\n"); post("Next literal was:\n"); dumpPyrSlot(slot); nodePostErrorLine(node); compileErrors++; return 0; } if (selectors->size + 1 > ARRAYMAXINDEXSIZE(selectors)) { // resize literal table newsize = ARRAYMAXINDEXSIZE(selectors) * 2; // resize literal table SetRaw(&func->selectors, (PyrObject*)newPyrArray(compileGC(), newsize, flags, false)); memcpy(slotRawObject(&func->selectors)->slots, selectors->slots, selectors->size * sizeof(PyrSlot)); slotRawObject(&func->selectors)->size = selectors->size; freePyrObject(selectors); selectors = slotRawObject(&func->selectors); } slot2 = selectors->slots + selectors->size++; slotCopy(slot2, slot); return selectors->size - 1; } int conjureConstantIndex(PyrParseNode* node, PyrBlock* func, PyrSlot* slot) { int i; PyrObject* constants; int newsize, flags; flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; // lookup slot in constants table if (IsObj(&func->constants)) { constants = slotRawObject(&func->constants); for (i = 0; i < constants->size; ++i) if (SlotEq(&constants->slots[i], slot)) return i; } else { constants = (PyrObject*)newPyrArray(compileGC(), 4, flags, false); SetObject(&func->constants, constants); } // otherwise add it to the constants table if (constants->size + 1 > ARRAYMAXINDEXSIZE(constants)) { // resize literal table newsize = ARRAYMAXINDEXSIZE(constants) * 2; // resize literal table SetRaw(&func->constants, (PyrObject*)newPyrArray(compileGC(), newsize, flags, false)); memcpy(slotRawObject(&func->constants)->slots, constants->slots, constants->size * sizeof(PyrSlot)); slotRawObject(&func->constants)->size = constants->size; freePyrObject((PyrObject*)constants); constants = slotRawObject(&func->constants); } slotCopy(&constants->slots[constants->size++], slot); return constants->size - 1; } bool findVarName(PyrBlock* func, PyrClass** classobj, PyrSymbol* name, int* varType, int* level, int* index, PyrBlock** tempfunc) { int i, j, k; int numargs; PyrSymbol *argname, *varname; PyrMethodRaw* methraw; // postfl("->findVarName %s\n", name->name); // find var in enclosing blocks, instance, class if (name == s_super) { gFunctionCantBeClosed = true; name = s_this; } if (name->name[0] >= 'A' && name->name[0] <= 'Z') return false; for (j = 0; func; func = slotRawBlock(&func->contextDef), ++j) { methraw = METHRAW(func); numargs = methraw->posargs; for (i = 0; i < numargs; ++i) { argname = slotRawSymbolArray(&func->argNames)->symbols[i]; // postfl(" %d %d arg '%s' '%s'\n", j, i, argname->name, name->name); if (argname == name) { *level = j; *index = i; *varType = varTemp; if (tempfunc) *tempfunc = func; if (j > gFunctionHighestExternalRef) gFunctionHighestExternalRef = j; return true; } } for (i = 0, k = numargs; i < methraw->numvars; ++i, ++k) { varname = slotRawSymbolArray(&func->varNames)->symbols[i]; // postfl(" %d %d %d var '%s' '%s'\n", j, i, k, varname->name, name->name); if (varname == name) { *level = j; *index = k; *varType = varTemp; if (tempfunc) *tempfunc = func; if (j > gFunctionHighestExternalRef) gFunctionHighestExternalRef = j; return true; } } } if (classFindInstVar(*classobj, name, index)) { *level = 0; *varType = varInst; if (gCompilingClass != class_interpreter) gFunctionCantBeClosed = true; return true; } if (classFindClassVar(classobj, name, index)) { *varType = varClass; if (gCompilingClass != class_interpreter) gFunctionCantBeClosed = true; return true; } if (classFindConst(classobj, name, index)) { *varType = varConst; // if (gCompilingClass != class_interpreter) gFunctionCantBeClosed = true; return true; } if (name == s_curProcess) { *varType = varPseudo; *index = opgProcess; return true; } if (name == s_curThread) { *varType = varPseudo; *index = opgThread; return true; } if (name == s_curMethod) { *varType = varPseudo; *index = opgMethod; return true; } if (name == s_curBlock) { *varType = varPseudo; *index = opgFunctionDef; return true; } if (name == s_curClosure) { *varType = varPseudo; *index = opgFunction; return true; } return false; } extern PyrSymbol* s_env; void initSpecialClasses() { gSpecialClasses[op_class_object] = s_object; gSpecialClasses[op_class_symbol] = s_symbol; gSpecialClasses[op_class_nil] = s_nil; gSpecialClasses[op_class_boolean] = s_boolean; gSpecialClasses[op_class_true] = s_true; gSpecialClasses[op_class_false] = s_false; gSpecialClasses[op_class_magnitude] = s_magnitude; gSpecialClasses[op_class_char] = s_char; gSpecialClasses[op_class_number] = s_number; gSpecialClasses[op_class_complex] = s_complex; gSpecialClasses[op_class_simple_number] = s_simple_number; gSpecialClasses[op_class_int] = s_int; gSpecialClasses[op_class_float] = s_float; gSpecialClasses[op_class_method] = s_method; gSpecialClasses[op_class_fundef] = s_fundef; gSpecialClasses[op_class_stream] = s_stream; gSpecialClasses[op_class_func] = s_func; gSpecialClasses[op_class_frame] = s_frame; gSpecialClasses[op_class_process] = s_process; gSpecialClasses[op_class_main] = s_main; gSpecialClasses[op_class_class] = s_class; gSpecialClasses[op_class_string] = s_string; gSpecialClasses[op_class_collection] = s_collection; gSpecialClasses[op_class_sequenceable_collection] = s_sequenceable_collection; gSpecialClasses[op_class_arrayed_collection] = s_arrayed_collection; gSpecialClasses[op_class_array] = s_array; gSpecialClasses[op_class_int8array] = s_int8array; gSpecialClasses[op_class_int16array] = s_int16array; gSpecialClasses[op_class_int32array] = s_int32array; gSpecialClasses[op_class_floatarray] = s_floatarray; gSpecialClasses[op_class_signal] = s_signal; gSpecialClasses[op_class_doublearray] = s_doublearray; gSpecialClasses[op_class_symbolarray] = s_symbolarray; gSpecialClasses[op_class_list] = s_list; gSpecialClasses[op_class_linkedlist] = s_linkedlist; gSpecialClasses[op_class_bag] = s_bag; gSpecialClasses[op_class_set] = s_set; gSpecialClasses[op_class_identityset] = s_identityset; gSpecialClasses[op_class_dictionary] = s_dictionary; gSpecialClasses[op_class_identitydictionary] = s_identitydictionary; gSpecialClasses[op_class_sortedlist] = s_sortedlist; gSpecialClasses[op_class_synth] = s_synth; gSpecialClasses[op_class_ref] = s_ref; gSpecialClasses[op_class_environment] = s_environment; gSpecialClasses[op_class_event] = s_event; gSpecialClasses[op_class_wavetable] = s_wavetable; gSpecialClasses[op_class_env] = s_env; gSpecialClasses[op_class_routine] = s_routine; gSpecialClasses[op_class_color] = s_color; gSpecialClasses[op_class_rect] = s_rect; // Infinitum, Point, Rect, ?? } void initSpecialSelectors() { PyrSymbol** sel; long i; sel = gSpecialUnarySelectors; sel[opNeg] = getsym("neg"); sel[opRecip] = getsym("reciprocal"); sel[opNot] = getsym("not"); sel[opIsNil] = getsym("isNil"); sel[opNotNil] = getsym("notNil"); sel[opBitNot] = getsym("bitNot"); sel[opAbs] = getsym("abs"); sel[opAsFloat] = getsym("asFloat"); sel[opAsInteger] = getsym("asInteger"); sel[opCeil] = getsym("ceil"); // 5 sel[opFloor] = getsym("floor"); sel[opFrac] = getsym("frac"); sel[opSign] = getsym("sign"); sel[opSquared] = getsym("squared"); sel[opCubed] = getsym("cubed"); // 10 sel[opSqrt] = getsym("sqrt"); sel[opExp] = getsym("exp"); sel[opMIDICPS] = getsym("midicps"); sel[opCPSMIDI] = getsym("cpsmidi"); sel[opMIDIRatio] = getsym("midiratio"); sel[opRatioMIDI] = getsym("ratiomidi"); sel[opAmpDb] = getsym("ampdb"); // 15 sel[opDbAmp] = getsym("dbamp"); sel[opOctCPS] = getsym("octcps"); sel[opCPSOct] = getsym("cpsoct"); sel[opLog] = getsym("log"); sel[opLog2] = getsym("log2"); // 20 sel[opLog10] = getsym("log10"); sel[opSin] = getsym("sin"); sel[opCos] = getsym("cos"); sel[opTan] = getsym("tan"); sel[opArcSin] = getsym("asin"); // 25 sel[opArcCos] = getsym("acos"); sel[opArcTan] = getsym("atan"); sel[opSinH] = getsym("sinh"); sel[opCosH] = getsym("cosh"); sel[opTanH] = getsym("tanh"); // 30 sel[opRand] = getsym("rand"); sel[opRand2] = getsym("rand2"); sel[opLinRand] = getsym("linrand"); sel[opBiLinRand] = getsym("bilinrand"); sel[opSum3Rand] = getsym("sum3rand"); /* sel[opExpRand] = getsym("exprand"); sel[opBiExpRand] = getsym("biexprand"); sel[opGammaRand] = getsym("gammarand"); sel[opGaussRand] = getsym("gaussrand"); sel[opPoiRand] = getsym("poirand"); */ sel[opDistort] = getsym("distort"); sel[opSoftClip] = getsym("softclip"); sel[opCoin] = getsym("coin"); sel[opRectWindow] = getsym("rectWindow"); sel[opHanWindow] = getsym("hanWindow"); sel[opWelchWindow] = getsym("welWindow"); sel[opTriWindow] = getsym("triWindow"); sel[opSCurve] = getsym("scurve"); sel[opRamp] = getsym("ramp"); sel[opDigitValue] = getsym("digitValue"); sel[opSilence] = getsym("silence"); sel[opThru] = getsym("thru"); sel = gSpecialBinarySelectors; sel[opAdd] = getsym("+"); sel[opSub] = getsym("-"); sel[opMul] = getsym("*"); sel[opFDiv] = getsym("/"); sel[opIDiv] = getsym("div"); sel[opMod] = getsym("mod"); sel[opEQ] = getsym("=="); sel[opNE] = getsym("!="); sel[opLT] = getsym("<"); sel[opGT] = getsym(">"); sel[opLE] = getsym("<="); sel[opGE] = getsym(">="); // sel[opIdentical] = getsym("==="); // sel[opNotIdentical] = getsym("!=="); sel[opMin] = getsym("min"); sel[opMax] = getsym("max"); sel[opBitAnd] = getsym("bitAnd"); sel[opBitOr] = getsym("bitOr"); sel[opBitXor] = getsym("bitXor"); sel[opLCM] = getsym("lcm"); sel[opGCD] = getsym("gcd"); sel[opRound] = getsym("round"); sel[opRoundUp] = getsym("roundUp"); sel[opTrunc] = getsym("trunc"); sel[opAtan2] = getsym("atan2"); sel[opHypot] = getsym("hypot"); sel[opHypotx] = getsym("hypotApx"); sel[opPow] = getsym("pow"); sel[opShiftLeft] = getsym("leftShift"); sel[opShiftRight] = getsym("rightShift"); sel[opUnsignedShift] = getsym("unsignedRightShift"); sel[opFill] = getsym("fill"); sel[opRing1] = getsym("ring1"); // a * (b + 1) == a * b + a sel[opRing2] = getsym("ring2"); // a * b + a + b sel[opRing3] = getsym("ring3"); // a*a*b sel[opRing4] = getsym("ring4"); // a*a*b - a*b*b sel[opDifSqr] = getsym("difsqr"); // a*a - b*b sel[opSumSqr] = getsym("sumsqr"); // a*a + b*b sel[opSqrSum] = getsym("sqrsum"); // (a + b)^2 sel[opSqrDif] = getsym("sqrdif"); // (a - b)^2 sel[opAbsDif] = getsym("absdif"); // sel[opThresh] = getsym("thresh"); // sel[opAMClip] = getsym("amclip"); // sel[opScaleNeg] = getsym("scaleneg"); // sel[opClip2] = getsym("clip2"); sel[opFold2] = getsym("fold2"); sel[opWrap2] = getsym("wrap2"); sel[opExcess] = getsym("excess"); sel[opFirstArg] = getsym("firstArg"); sel[opRandRange] = getsym("rrand"); sel[opExpRandRange] = getsym("exprand"); sel = gSpecialSelectors; sel[opmNew] = getsym("new"); sel[opmNewClear] = getsym("newClear"); sel[opmNewCopyArgs] = getsym("newCopyArgs"); sel[opmInit] = getsym("init"); sel[opmAt] = getsym("at"); sel[opmPut] = getsym("put"); sel[opmNext] = getsym("next"); sel[opmReset] = getsym("reset"); sel[opmValue] = getsym("value"); sel[opmCopyToEnd] = getsym("copyToEnd"); // used by multiple assignment // sel[opmIsNil] = getsym("isNil"); // sel[opmNotNil] = getsym("notNil"); sel[opmSize] = getsym("size"); sel[opmClass] = getsym("class"); sel[opmIf] = getsym("if"); sel[opmWhile] = getsym("while"); sel[opmFor] = getsym("for"); sel[opmAnd] = getsym("and"); sel[opmOr] = getsym("or"); sel[opmCase] = getsym("case"); sel[opmSwitch] = getsym("switch"); sel[opmIdentical] = getsym("==="); sel[opmNotIdentical] = getsym("!=="); sel[opmPrint] = getsym("print"); sel[opmAdd] = getsym("add"); sel[opmRemove] = getsym("remove"); sel[opmIndexOf] = getsym("indexOf"); sel[opmWrapAt] = getsym("wrapAt"); sel[opmClipAt] = getsym("clipAt"); sel[opmFoldAt] = getsym("foldAt"); sel[opmWrapPut] = getsym("wrapPut"); sel[opmClipPut] = getsym("clipPut"); sel[opmFoldPut] = getsym("foldPut"); sel[opmDo] = getsym("do"); sel[opmCollect] = getsym("collect"); sel[opmSelect] = getsym("select"); sel[opmReject] = getsym("reject"); sel[opmAny] = getsym("any"); sel[opmEvery] = getsym("every"); sel[opmFind] = getsym("find"); sel[opmChoose] = getsym("choose"); sel[opmValueList] = getsym("valueList"); sel[opmAddFirst] = getsym("addFirst"); sel[opmPrimitiveFailed] = getsym("primitiveFailed"); sel[opmSubclassResponsibility] = getsym("subclassResponsibility"); sel[opmShouldNotImplement] = getsym("shouldNotImplement"); sel[opmDoesNotUnderstand] = getsym("doesNotUnderstand"); // not really needed sel[opmNotYetImplemented] = getsym("notYetImplemented"); sel[opmAtSign] = getsym("@"); sel[opmWrapAtSign] = getsym("@@"); sel[opmClipAtSign] = getsym("|@|"); sel[opmFoldAtSign] = getsym("@|@"); sel[opmMultiNew] = getsym("multiNew"); // UGens sel[opmMultiNewList] = getsym("multiNewList"); // UGens sel[opmAR] = getsym("ar"); // UGens sel[opmKR] = getsym("kr"); // UGens sel[opmIR] = getsym("ir"); // UGens sel[opmEnvirGet] = getsym("envirGet"); sel[opmEnvirPut] = getsym("envirPut"); sel[opmHalt] = getsym("halt"); sel[opmForBy] = getsym("forBy"); sel[opmForSeries] = getsym("forSeries"); sel[opmReverseDo] = getsym("reverseDo"); sel[opmLoop] = getsym("loop"); sel[opmNonBooleanError] = getsym("mustBeBoolean"); sel[opmCopy] = getsym("copy"); sel[opmPerformList] = getsym("performList"); sel[opmIsKindOf] = getsym("isKindOf"); sel[opmPostln] = getsym("postln"); sel[opmAsString] = getsym("asString"); sel[opmPlusPlus] = getsym("++"); sel[opmLTLT] = getsym("<<"); sel[opmQuestionMark] = getsym("?"); sel[opmDoubleQuestionMark] = getsym("??"); sel[opmExclamationQuestionMark] = getsym("!?"); sel[opmYield] = getsym("yield"); sel[opmName] = getsym("name"); sel[opmMulAdd] = getsym("madd"); sel[opmSeries] = getsym("series"); for (i = 0; i < opNumUnarySelectors; ++i) { gSpecialUnarySelectors[i]->specialIndex = i; } for (i = 0; i < opNumBinarySelectors; ++i) { gSpecialBinarySelectors[i]->specialIndex = i; } } bool findSpecialClassName(PyrSymbol* className, int* index) { int i; for (i = 0; i < op_NumSpecialClasses; ++i) { if (gSpecialClasses[i] == className) { *index = i; return true; } } return false; }
170,237
C++
.cpp
4,189
30.703748
120
0.59359
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,843
PyrMathOps.cpp
supercollider_supercollider/lang/LangSource/PyrMathOps.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <math.h> #include <stdlib.h> #include <string.h> #include "Opcodes.h" #include "PyrInterpreter.h" #include "PyrPrimitive.h" #include "PyrPrimitiveProto.h" #include "PyrMathPrim.h" #include "PyrKernel.h" #include "PyrMessage.h" #include "PyrParseNode.h" #include "PyrSignal.h" #include "PyrSched.h" #include "PyrSymbol.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "MiscInlineMath.h" #include "PyrKernelProto.h" #include <limits> double hypotx(double x, double y); #define IS_BINARY_BOOL_OP(op) ((op) >= opEQ && (op) <= opGE) int doSpecialUnaryArithMsg(VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrSymbol* msg; int opcode = g->primitiveIndex; a = g->sp; switch (GetTag(a)) { case tagInt: switch (opcode) { case opNeg: SetRaw(a, -slotRawInt(a)); break; // case opNot : goto send_normal_1; case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; case opBitNot: SetRaw(a, ~slotRawInt(a)); break; case opAbs: SetRaw(a, sc_abs(slotRawInt(a))); break; case opAsFloat: SetFloat(a, (double)slotRawInt(a)); break; case opAsInteger: SetRaw(a, (int)slotRawInt(a)); break; case opCeil: SetRaw(a, slotRawInt(a)); break; case opFloor: SetRaw(a, slotRawInt(a)); break; case opFrac: SetRaw(a, 0); break; case opSign: SetRaw(a, slotRawInt(a) > 0 ? 1 : (slotRawInt(a) == 0 ? 0 : -1)); break; case opSquared: SetRaw(a, slotRawInt(a) * slotRawInt(a)); break; case opCubed: SetRaw(a, slotRawInt(a) * slotRawInt(a) * slotRawInt(a)); break; case opSqrt: SetFloat(a, sqrt((double)slotRawInt(a))); break; case opExp: SetFloat(a, exp((double)slotRawInt(a))); break; case opRecip: SetFloat(a, 1. / slotRawInt(a)); break; case opMIDICPS: SetFloat(a, sc_midicps((double)slotRawInt(a))); break; case opCPSMIDI: SetFloat(a, sc_cpsmidi((double)slotRawInt(a))); break; case opMIDIRatio: SetFloat(a, sc_midiratio((double)slotRawInt(a))); break; case opRatioMIDI: SetFloat(a, sc_ratiomidi((double)slotRawInt(a))); break; case opAmpDb: SetFloat(a, sc_ampdb((double)slotRawInt(a))); break; case opDbAmp: SetFloat(a, sc_dbamp((double)slotRawInt(a))); break; case opOctCPS: SetFloat(a, sc_octcps((double)slotRawInt(a))); break; case opCPSOct: SetFloat(a, sc_cpsoct((double)slotRawInt(a))); break; case opLog: SetFloat(a, log((double)slotRawInt(a))); break; case opLog2: SetFloat(a, sc_log2((double)slotRawInt(a))); break; case opLog10: SetFloat(a, log10((double)slotRawInt(a))); break; case opSin: SetFloat(a, sin((double)slotRawInt(a))); break; case opCos: SetFloat(a, cos((double)slotRawInt(a))); break; case opTan: SetFloat(a, tan((double)slotRawInt(a))); break; case opArcSin: SetFloat(a, asin((double)slotRawInt(a))); break; case opArcCos: SetFloat(a, acos((double)slotRawInt(a))); break; case opArcTan: SetFloat(a, atan((double)slotRawInt(a))); break; case opSinH: SetFloat(a, sinh((double)slotRawInt(a))); break; case opCosH: SetFloat(a, cosh((double)slotRawInt(a))); break; case opTanH: SetFloat(a, tanh((double)slotRawInt(a))); break; case opRand: SetRaw(a, g->rgen->irand(slotRawInt(a))); break; case opRand2: SetRaw(a, g->rgen->irand2(slotRawInt(a))); break; case opLinRand: SetRaw(a, g->rgen->ilinrand(slotRawInt(a))); break; case opBiLinRand: SetRaw(a, g->rgen->ibilinrand(slotRawInt(a))); break; // case opExpRand : SetFloat(a, g->rgen->exprand(slotRawInt(a))); break; // case opBiExpRand : SetFloat(a, g->rgen->biexprand(slotRawInt(a))); break; case opSum3Rand: SetFloat(a, g->rgen->sum3rand(slotRawInt(a))); break; // case opGammaRand : SetFloat(a, g->rgen->gammarand(slotRawInt(a))); break; // case opGaussRand : SetFloat(a, g->rgen->gaussrand(slotRawInt(a))); break; // case opPoiRand : SetFloat(a, g->rgen->poirand(slotRawInt(a))); break; case opDistort: SetFloat(a, sc_distort((double)slotRawInt(a))); break; case opSoftClip: SetFloat(a, sc_softclip((double)slotRawInt(a))); break; case opCoin: SetBool(a, (slotRawInt(a))); break; case opRectWindow: SetFloat(a, sc_rectwindow((double)slotRawInt(a))); break; case opHanWindow: SetFloat(a, sc_hanwindow((double)slotRawInt(a))); break; case opWelchWindow: SetFloat(a, sc_welwindow((double)slotRawInt(a))); break; case opTriWindow: SetFloat(a, sc_triwindow((double)slotRawInt(a))); break; case opSCurve: SetFloat(a, sc_scurve((double)slotRawInt(a))); break; case opRamp: SetFloat(a, sc_ramp((double)slotRawInt(a))); break; default: goto send_normal_1; } break; case tagChar: switch (opcode) { // case opNot : goto send_normal_1; case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; case opAsInteger: SetTagRaw(a, tagInt); break; case opDigitValue: if (slotRawInt(a) >= '0' && slotRawInt(a) <= '9') SetInt(a, slotRawInt(a) - '0'); else if (slotRawInt(a) >= 'A' && slotRawInt(a) <= 'Z') SetInt(a, slotRawInt(a) - 'A'); else if (slotRawInt(a) >= 'a' && slotRawInt(a) <= 'z') SetInt(a, slotRawInt(a) - 'a'); else SetInt(a, 0); break; default: goto send_normal_1; } break; case tagPtr: switch (opcode) { case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; default: goto send_normal_1; } break; case tagNil: switch (opcode) { case opIsNil: SetTrue(a); break; case opNotNil: SetFalse(a); break; default: goto send_normal_1; } break; case tagFalse: switch (opcode) { case opNot: SetTrue(a); break; case opIsNil: /*SetFalse(a);*/ break; case opNotNil: SetTrue(a); break; default: goto send_normal_1; } break; case tagTrue: switch (opcode) { case opNot: SetFalse(a); break; case opIsNil: SetFalse(a); break; case opNotNil: /*SetTrue(a);*/ break; default: goto send_normal_1; } break; case tagSym: switch (opcode) { case opAsFloat: case opAsInteger: goto send_normal_1; case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; default: /* SetSymbol(a, slotRawSymbol(a)); */ break; } break; case tagObj: if (isKindOf(slotRawObject(a), class_signal)) { switch (opcode) { case opNeg: SetRaw(a, signal_invert(g, slotRawObject(a))); break; case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; case opAbs: SetRaw(a, signal_abs(g, slotRawObject(a))); break; case opSign: SetRaw(a, signal_sign(g, slotRawObject(a))); break; case opSquared: SetRaw(a, signal_squared(g, slotRawObject(a))); break; case opCubed: SetRaw(a, signal_cubed(g, slotRawObject(a))); break; case opSqrt: SetRaw(a, signal_sqrt(g, slotRawObject(a))); break; case opExp: SetRaw(a, signal_exp(g, slotRawObject(a))); break; case opRecip: SetRaw(a, signal_recip(g, slotRawObject(a))); break; case opLog: SetRaw(a, signal_log(g, slotRawObject(a))); break; case opLog2: SetRaw(a, signal_log2(g, slotRawObject(a))); break; case opLog10: SetRaw(a, signal_log10(g, slotRawObject(a))); break; case opSin: SetRaw(a, signal_sin(g, slotRawObject(a))); break; // case opSin : SetRaw(a, signal_fsin(g, slotRawObject(a))); break; case opCos: SetRaw(a, signal_cos(g, slotRawObject(a))); break; case opTan: SetRaw(a, signal_tan(g, slotRawObject(a))); break; case opArcSin: SetRaw(a, signal_asin(g, slotRawObject(a))); break; case opArcCos: SetRaw(a, signal_acos(g, slotRawObject(a))); break; case opArcTan: SetRaw(a, signal_atan(g, slotRawObject(a))); break; case opSinH: SetRaw(a, signal_sinh(g, slotRawObject(a))); break; case opCosH: SetRaw(a, signal_cosh(g, slotRawObject(a))); break; case opTanH: SetRaw(a, signal_tanh(g, slotRawObject(a))); break; case opDistort: SetRaw(a, signal_distort(g, slotRawObject(a))); break; case opSoftClip: SetRaw(a, signal_softclip(g, slotRawObject(a))); break; default: goto send_normal_1; } } else { goto send_normal_1; } break; default: // double switch (opcode) { case opNeg: SetRaw(a, -slotRawFloat(a)); break; case opIsNil: SetFalse(a); break; case opNotNil: SetTrue(a); break; case opBitNot: SetRaw(a, ~(int)slotRawFloat(a)); break; case opAbs: SetRaw(a, sc_abs(slotRawFloat(a))); break; case opAsFloat: SetRaw(a, (double)slotRawFloat(a)); break; case opAsInteger: { double val = slotRawFloat(a); if (val == std::numeric_limits<double>::infinity()) SetInt(a, std::numeric_limits<int>::max()); else SetInt(a, (int)val); break; } case opCeil: SetRaw(a, ceil(slotRawFloat(a))); break; case opFloor: SetRaw(a, floor(slotRawFloat(a))); break; case opFrac: SetRaw(a, sc_frac(slotRawFloat(a))); break; case opSign: SetRaw(a, slotRawFloat(a) > 0. ? 1.0 : (slotRawFloat(a) == 0 ? 0.0 : -1.0)); break; case opSquared: SetRaw(a, slotRawFloat(a) * slotRawFloat(a)); break; case opCubed: SetRaw(a, slotRawFloat(a) * slotRawFloat(a) * slotRawFloat(a)); break; case opSqrt: SetRaw(a, sqrt(slotRawFloat(a))); break; case opExp: SetRaw(a, exp(slotRawFloat(a))); break; case opRecip: SetRaw(a, 1. / slotRawFloat(a)); break; case opMIDICPS: SetRaw(a, sc_midicps(slotRawFloat(a))); break; case opCPSMIDI: SetRaw(a, sc_cpsmidi(slotRawFloat(a))); break; case opMIDIRatio: SetRaw(a, sc_midiratio((double)slotRawFloat(a))); break; case opRatioMIDI: SetRaw(a, sc_ratiomidi((double)slotRawFloat(a))); break; case opAmpDb: SetRaw(a, sc_ampdb(slotRawFloat(a))); break; case opDbAmp: SetRaw(a, sc_dbamp(slotRawFloat(a))); break; case opOctCPS: SetRaw(a, sc_octcps(slotRawFloat(a))); break; case opCPSOct: SetRaw(a, sc_cpsoct(slotRawFloat(a))); break; case opLog: SetRaw(a, log(slotRawFloat(a))); break; case opLog2: SetRaw(a, sc_log2(slotRawFloat(a))); break; case opLog10: SetRaw(a, log10(slotRawFloat(a))); break; case opSin: SetRaw(a, sin(slotRawFloat(a))); break; case opCos: SetRaw(a, cos(slotRawFloat(a))); break; case opTan: SetRaw(a, tan(slotRawFloat(a))); break; case opArcSin: SetRaw(a, asin(slotRawFloat(a))); break; case opArcCos: SetRaw(a, acos(slotRawFloat(a))); break; case opArcTan: SetRaw(a, atan(slotRawFloat(a))); break; case opSinH: SetRaw(a, sinh(slotRawFloat(a))); break; case opCosH: SetRaw(a, cosh(slotRawFloat(a))); break; case opTanH: SetRaw(a, tanh(slotRawFloat(a))); break; case opRand: SetRaw(a, g->rgen->frand() * slotRawFloat(a)); break; case opRand2: SetRaw(a, g->rgen->frand2() * slotRawFloat(a)); break; case opLinRand: SetRaw(a, g->rgen->linrand(slotRawFloat(a))); break; case opBiLinRand: SetRaw(a, g->rgen->bilinrand(slotRawFloat(a))); break; // case opExpRand : SetRaw(a, g->rgen->exprand(slotRawFloat(a))); break; // case opBiExpRand : SetRaw(a, g->rgen->biexprand(slotRawFloat(a))); break; case opSum3Rand: SetRaw(a, g->rgen->sum3rand(slotRawFloat(a))); break; // case opGammaRand : SetRaw(a, g->rgen->gammarand(slotRawFloat(a))); break; // case opGaussRand : SetRaw(a, g->rgen->gaussrand(slotRawFloat(a))); break; // case opPoiRand : SetRaw(a, g->rgen->poirand(slotRawFloat(a))); break; case opDistort: SetRaw(a, sc_distort(slotRawFloat(a))); break; case opSoftClip: SetRaw(a, sc_softclip(slotRawFloat(a))); break; case opCoin: SetBool(a, g->rgen->frand() < slotRawFloat(a)); break; case opRectWindow: SetRaw(a, sc_rectwindow(slotRawFloat(a))); break; case opHanWindow: SetRaw(a, sc_hanwindow(slotRawFloat(a))); break; case opWelchWindow: SetRaw(a, sc_welwindow(slotRawFloat(a))); break; case opTriWindow: SetRaw(a, sc_triwindow(slotRawFloat(a))); break; case opSCurve: SetRaw(a, sc_scurve(slotRawFloat(a))); break; case opRamp: SetRaw(a, sc_ramp(slotRawFloat(a))); break; default: goto send_normal_1; } break; } #if TAILCALLOPTIMIZE g->tailCall = 0; #endif return errNone; send_normal_1: if (numArgsPushed != -1) // special case flag meaning it is a primitive return errFailed; msg = gSpecialUnarySelectors[opcode]; sendMessage(g, msg, 1, 0); return errNone; } int prSpecialBinaryArithMsg(VMGlobals* g, int numArgsPushed) { return doSpecialBinaryArithMsg(g, numArgsPushed, true); } int doSpecialBinaryArithMsg(VMGlobals* g, int numArgsPushed, bool isPrimitive) { PyrSlot *a, *b; PyrSymbol* msg; int opcode = g->primitiveIndex; a = g->sp - (numArgsPushed - 1); b = a + 1; switch (GetTag(a)) { case tagInt: { switch (GetTag(b)) { case tagInt: switch (opcode) { case opAdd: SetRaw(a, slotRawInt(a) + slotRawInt(b)); break; case opSub: SetRaw(a, slotRawInt(a) - slotRawInt(b)); break; case opMul: SetRaw(a, slotRawInt(a) * slotRawInt(b)); break; case opIDiv: SetRaw(a, sc_div(slotRawInt(a), slotRawInt(b))); break; case opFDiv: SetFloat(a, (double)slotRawInt(a) / (double)slotRawInt(b)); break; case opMod: SetRaw(a, sc_mod((int)slotRawInt(a), (int)slotRawInt(b))); break; case opEQ: SetBool(a, slotRawInt(a) == slotRawInt(b)); break; case opNE: SetBool(a, slotRawInt(a) != slotRawInt(b)); break; case opLT: SetBool(a, slotRawInt(a) < slotRawInt(b)); break; case opGT: SetBool(a, slotRawInt(a) > slotRawInt(b)); break; case opLE: SetBool(a, slotRawInt(a) <= slotRawInt(b)); break; case opGE: SetBool(a, slotRawInt(a) >= slotRawInt(b)); break; // case opIdentical : SetBool(a, slotRawInt(a) == slotRawInt(b)); break; // case opNotIdentical : SetBool(a, slotRawInt(a) != slotRawInt(b)); break; case opMin: SetRaw(a, sc_min(slotRawInt(a), slotRawInt(b))); break; case opMax: SetRaw(a, sc_max(slotRawInt(a), slotRawInt(b))); break; case opBitAnd: SetRaw(a, slotRawInt(a) & slotRawInt(b)); break; case opBitOr: SetRaw(a, slotRawInt(a) | slotRawInt(b)); break; case opBitXor: SetRaw(a, slotRawInt(a) ^ slotRawInt(b)); break; case opLCM: SetRaw(a, sc_lcm((long)slotRawInt(a), (long)slotRawInt(b))); break; case opGCD: SetRaw(a, sc_gcd((long)slotRawInt(a), (long)slotRawInt(b))); break; case opRound: SetRaw(a, sc_round((int)slotRawInt(a), (int)slotRawInt(b))); break; case opRoundUp: SetRaw(a, sc_roundUp((int)slotRawInt(a), (int)slotRawInt(b))); break; case opTrunc: SetRaw(a, sc_trunc((int)slotRawInt(a), (int)slotRawInt(b))); break; case opAtan2: SetFloat(a, atan2((double)slotRawInt(a), (double)slotRawInt(b))); break; case opHypot: SetFloat(a, hypot((double)slotRawInt(a), (double)slotRawInt(b))); break; case opHypotx: SetFloat(a, hypotx((double)slotRawInt(a), (double)slotRawInt(b))); break; case opPow: SetFloat(a, pow((double)slotRawInt(a), (double)slotRawInt(b))); break; case opShiftLeft: { long ia = slotRawInt(a); long ib = slotRawInt(b); if (ib > 0) ia <<= ib; else if (ib < 0) ia >>= -ib; SetRaw(a, ia); } break; case opShiftRight: { long ia = slotRawInt(a); long ib = slotRawInt(b); if (ib > 0) ia >>= ib; else if (ib < 0) ia <<= -ib; SetRaw(a, ia); } break; case opUnsignedShift: { unsigned long ia = slotRawInt(a); long ib = slotRawInt(b); if (ib > 0) ia >>= ib; else if (ib < 0) ia <<= -ib; SetRaw(a, (long)ia); } break; case opRing1: SetRaw(a, sc_ring1(slotRawInt(a), slotRawInt(b))); break; case opRing2: SetRaw(a, sc_ring2(slotRawInt(a), slotRawInt(b))); break; case opRing3: SetRaw(a, sc_ring3(slotRawInt(a), slotRawInt(b))); break; case opRing4: SetRaw(a, sc_ring4(slotRawInt(a), slotRawInt(b))); break; case opDifSqr: SetRaw(a, sc_difsqr(slotRawInt(a), slotRawInt(b))); break; case opSumSqr: SetRaw(a, sc_sumsqr(slotRawInt(a), slotRawInt(b))); break; case opSqrSum: SetRaw(a, sc_sqrsum(slotRawInt(a), slotRawInt(b))); break; case opSqrDif: SetRaw(a, sc_sqrdif(slotRawInt(a), slotRawInt(b))); break; case opAbsDif: SetRaw(a, sc_abs(slotRawInt(a) - slotRawInt(b))); break; case opThresh: SetRaw(a, sc_thresh(slotRawInt(a), slotRawInt(b))); break; case opAMClip: SetRaw(a, sc_amclip(slotRawInt(a), slotRawInt(b))); break; case opScaleNeg: SetRaw(a, sc_scaleneg(slotRawInt(a), slotRawInt(b))); break; case opClip2: SetRaw(a, sc_clip2(slotRawInt(a), slotRawInt(b))); break; case opFold2: SetRaw(a, sc_fold2(slotRawInt(a), slotRawInt(b))); break; case opWrap2: SetRaw(a, sc_wrap2(slotRawInt(a), slotRawInt(b))); break; case opExcess: SetRaw(a, sc_excess(slotRawInt(a), slotRawInt(b))); break; case opFirstArg: SetRaw(a, slotRawInt(a)); break; case opRandRange: SetRaw(a, slotRawInt(b) > slotRawInt(a) ? slotRawInt(a) + g->rgen->irand(slotRawInt(b) - slotRawInt(a) + 1) : slotRawInt(b) + g->rgen->irand(slotRawInt(a) - slotRawInt(b) + 1)); break; case opExpRandRange: SetFloat(a, g->rgen->exprandrng(slotRawInt(a), slotRawInt(b))); break; default: goto send_normal_2; } break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: if (IS_BINARY_BOOL_OP(opcode)) SetBool(a, opcode == opNE); else SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) { switch (opcode) { case opAdd: SetObject(a, signal_add_xf(g, slotRawObject(b), slotRawInt(a))); break; case opSub: SetObject(a, signal_sub_fx(g, slotRawInt(a), slotRawObject(b))); break; case opMul: SetObject(a, signal_mul_xf(g, slotRawObject(b), slotRawInt(a))); break; case opIDiv: SetObject(a, signal_div_fx(g, slotRawInt(a), slotRawObject(b))); break; case opFDiv: SetObject(a, signal_div_fx(g, slotRawInt(a), slotRawObject(b))); break; case opEQ: SetFalse(a); break; case opNE: SetTrue(a); break; case opMin: SetObject(a, signal_min_xf(g, slotRawObject(b), slotRawInt(a))); break; case opMax: SetObject(a, signal_max_xf(g, slotRawObject(b), slotRawInt(a))); break; case opRing1: SetObject(a, signal_ring1_fx(g, slotRawInt(a), slotRawObject(b))); break; case opRing2: SetObject(a, signal_ring2_fx(g, slotRawInt(a), slotRawObject(b))); break; case opRing3: SetObject(a, signal_ring3_fx(g, slotRawInt(a), slotRawObject(b))); break; case opRing4: SetObject(a, signal_ring4_fx(g, slotRawInt(a), slotRawObject(b))); break; case opDifSqr: SetObject(a, signal_difsqr_fx(g, slotRawInt(a), slotRawObject(b))); break; case opSumSqr: SetObject(a, signal_sumsqr_fx(g, slotRawInt(a), slotRawObject(b))); break; case opSqrSum: SetObject(a, signal_sqrsum_fx(g, slotRawInt(a), slotRawObject(b))); break; case opSqrDif: SetObject(a, signal_sqrdif_fx(g, slotRawInt(a), slotRawObject(b))); break; case opAbsDif: SetObject(a, signal_absdif_fx(g, slotRawInt(a), slotRawObject(b))); break; case opThresh: SetObject(a, signal_thresh_fx(g, slotRawInt(a), slotRawObject(b))); break; case opAMClip: SetObject(a, signal_amclip_fx(g, slotRawInt(a), slotRawObject(b))); break; case opScaleNeg: SetObject(a, signal_scaleneg_fx(g, slotRawInt(a), slotRawObject(b))); break; case opClip2: SetObject(a, signal_clip2_fx(g, slotRawInt(a), slotRawObject(b))); break; case opFold2: SetObject(a, signal_fold2_fx(g, slotRawInt(a), slotRawObject(b))); break; case opWrap2: SetObject(a, signal_wrap2_fx(g, slotRawInt(a), slotRawObject(b))); break; case opExcess: SetObject(a, signal_excess_fx(g, slotRawInt(a), slotRawObject(b))); break; case opFirstArg: SetObject(a, slotRawObject(a)); break; default: goto send_normal_2; } } else { goto send_normal_2; } break; default: switch (opcode) { case opAdd: SetFloat(a, slotRawInt(a) + slotRawFloat(b)); break; case opSub: SetFloat(a, slotRawInt(a) - slotRawFloat(b)); break; case opMul: SetFloat(a, slotRawInt(a) * slotRawFloat(b)); break; case opIDiv: SetRaw(a, (long)floor(slotRawInt(a) / slotRawFloat(b))); break; case opFDiv: SetFloat(a, slotRawInt(a) / slotRawFloat(b)); break; case opMod: SetFloat(a, sc_mod((double)slotRawInt(a), slotRawFloat(b))); break; case opEQ: SetBool(a, slotRawInt(a) == slotRawFloat(b)); break; case opNE: SetBool(a, slotRawInt(a) != slotRawFloat(b)); break; case opLT: SetBool(a, slotRawInt(a) < slotRawFloat(b)); break; case opGT: SetBool(a, slotRawInt(a) > slotRawFloat(b)); break; case opLE: SetBool(a, slotRawInt(a) <= slotRawFloat(b)); break; case opGE: SetBool(a, slotRawInt(a) >= slotRawFloat(b)); break; // case opIdentical : SetFalse(a); break; // case opNotIdentical : SetTrue(a); break; case opMin: SetFloat(a, sc_min((double)slotRawInt(a), slotRawFloat(b))); break; case opMax: SetFloat(a, sc_max((double)slotRawInt(a), slotRawFloat(b))); break; case opRound: SetFloat(a, sc_round((double)slotRawInt(a), slotRawFloat(b))); break; case opRoundUp: SetFloat(a, sc_roundUp((double)slotRawInt(a), slotRawFloat(b))); break; case opTrunc: SetFloat(a, sc_trunc((double)slotRawInt(a), slotRawFloat(b))); break; case opAtan2: SetFloat(a, atan2(slotRawInt(a), slotRawFloat(b))); break; case opHypot: SetFloat(a, hypot(slotRawInt(a), slotRawFloat(b))); break; case opHypotx: SetFloat(a, hypotx(slotRawInt(a), slotRawFloat(b))); break; case opPow: SetFloat(a, pow((double)slotRawInt(a), slotRawFloat(b))); break; case opRing1: SetFloat(a, sc_ring1((double)slotRawInt(a), slotRawFloat(b))); break; case opRing2: SetFloat(a, sc_ring2((double)slotRawInt(a), slotRawFloat(b))); break; case opRing3: SetFloat(a, sc_ring3((double)slotRawInt(a), slotRawFloat(b))); break; case opRing4: SetFloat(a, sc_ring4((double)slotRawInt(a), slotRawFloat(b))); break; case opDifSqr: SetFloat(a, sc_difsqr((double)slotRawInt(a), slotRawFloat(b))); break; case opSumSqr: SetFloat(a, sc_sumsqr((double)slotRawInt(a), slotRawFloat(b))); break; case opSqrSum: SetFloat(a, sc_sqrsum((double)slotRawInt(a), slotRawFloat(b))); break; case opSqrDif: SetFloat(a, sc_sqrdif((double)slotRawInt(a), slotRawFloat(b))); break; case opAbsDif: SetFloat(a, sc_abs(slotRawInt(a) - slotRawFloat(b))); break; case opThresh: SetRaw(a, sc_thresh(slotRawInt(a), slotRawFloat(b))); break; case opAMClip: SetFloat(a, sc_amclip((double)slotRawInt(a), slotRawFloat(b))); break; case opScaleNeg: SetFloat(a, sc_scaleneg((double)slotRawInt(a), slotRawFloat(b))); break; case opClip2: SetFloat(a, sc_clip2((double)slotRawInt(a), slotRawFloat(b))); break; case opFold2: SetFloat(a, sc_fold2((double)slotRawInt(a), slotRawFloat(b))); break; case opWrap2: SetFloat(a, sc_wrap2((double)slotRawInt(a), -slotRawFloat(b))); break; case opExcess: SetFloat(a, sc_excess((double)slotRawInt(a), slotRawFloat(b))); break; case opFirstArg: SetInt(a, slotRawInt(a)); break; case opRandRange: SetFloat(a, slotRawInt(a) + g->rgen->frand() * (slotRawFloat(b) - slotRawInt(a))); break; case opExpRandRange: SetFloat(a, g->rgen->exprandrng(slotRawInt(a), slotRawFloat(b))); break; default: goto send_normal_2; } break; } } break; case tagChar: { if (IsChar(b)) { switch (opcode) { case opEQ: SetBool(a, slotRawChar(a) == slotRawChar(b)); break; case opNE: SetBool(a, slotRawChar(a) != slotRawChar(b)); break; case opLT: SetBool(a, slotRawChar(a) < slotRawChar(b)); break; case opGT: SetBool(a, slotRawChar(a) > slotRawChar(b)); break; case opLE: SetBool(a, slotRawChar(a) <= slotRawChar(b)); break; case opGE: SetBool(a, slotRawChar(a) >= slotRawChar(b)); break; // case opIdentical : SetBool(a, slotRawChar(a) == slotRawChar(b)); break; // case opNotIdentical : SetBool(a, slotRawChar(a) != slotRawChar(b)); break; case opMin: SetRawChar(a, sc_min(slotRawChar(a), slotRawChar(b))); break; case opMax: SetRawChar(a, sc_max(slotRawChar(a), slotRawChar(b))); break; default: goto send_normal_2; } } else { goto send_normal_2; } } break; case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: if (IsSym(b)) { switch (opcode) { case opEQ: SetBool(a, slotRawSymbol(a) == slotRawSymbol(b)); break; case opNE: SetBool(a, slotRawSymbol(a) != slotRawSymbol(b)); break; case opLT: SetBool(a, strcmp(slotRawSymbol(a)->name, slotRawSymbol(b)->name) < 0); break; case opGT: SetBool(a, strcmp(slotRawSymbol(a)->name, slotRawSymbol(b)->name) > 0); break; case opLE: SetBool(a, strcmp(slotRawSymbol(a)->name, slotRawSymbol(b)->name) <= 0); break; case opGE: SetBool(a, strcmp(slotRawSymbol(a)->name, slotRawSymbol(b)->name) >= 0); break; // default : leave first operand on stack } } else { if (IS_BINARY_BOOL_OP(opcode)) SetBool(a, opcode == opNE); } break; case tagObj: { if (isKindOf(slotRawObject(a), class_signal)) { switch (GetTag(b)) { case tagInt: switch (opcode) { case opAdd: SetRaw(a, signal_add_xf(g, slotRawObject(a), slotRawInt(b))); break; case opSub: SetRaw(a, signal_sub_xf(g, slotRawObject(a), slotRawInt(b))); break; case opMul: SetRaw(a, signal_mul_xf(g, slotRawObject(a), slotRawInt(b))); break; case opIDiv: SetRaw(a, signal_div_xf(g, slotRawObject(a), slotRawInt(b))); break; case opFDiv: SetRaw(a, signal_div_xf(g, slotRawObject(a), slotRawInt(b))); break; case opEQ: SetFalse(a); break; case opNE: SetTrue(a); break; case opMin: SetRaw(a, signal_min_xf(g, slotRawObject(a), slotRawInt(b))); break; case opMax: SetRaw(a, signal_max_xf(g, slotRawObject(a), slotRawInt(b))); break; case opFill: SetRaw(a, signal_fill(slotRawObject(a), slotRawInt(b))); break; case opRing1: SetRaw(a, signal_ring1_xf(g, slotRawObject(a), slotRawInt(b))); break; case opRing2: SetRaw(a, signal_ring2_xf(g, slotRawObject(a), slotRawInt(b))); break; case opRing3: SetRaw(a, signal_ring3_xf(g, slotRawObject(a), slotRawInt(b))); break; case opRing4: SetRaw(a, signal_ring4_xf(g, slotRawObject(a), slotRawInt(b))); break; case opDifSqr: SetRaw(a, signal_difsqr_xf(g, slotRawObject(a), slotRawInt(b))); break; case opSumSqr: SetRaw(a, signal_sumsqr_xf(g, slotRawObject(a), slotRawInt(b))); break; case opSqrSum: SetRaw(a, signal_sqrsum_xf(g, slotRawObject(a), slotRawInt(b))); break; case opSqrDif: SetRaw(a, signal_sqrdif_xf(g, slotRawObject(a), slotRawInt(b))); break; case opAbsDif: SetRaw(a, signal_absdif_xf(g, slotRawObject(a), slotRawInt(b))); break; case opThresh: SetRaw(a, signal_thresh_xf(g, slotRawObject(a), slotRawInt(b))); break; case opAMClip: SetRaw(a, signal_amclip_xf(g, slotRawObject(a), slotRawInt(b))); break; case opScaleNeg: SetRaw(a, signal_scaleneg_xf(g, slotRawObject(a), slotRawInt(b))); break; case opClip2: SetRaw(a, signal_clip2_xf(g, slotRawObject(a), slotRawInt(b))); break; case opFold2: SetRaw(a, signal_fold2_xf(g, slotRawObject(a), slotRawInt(b))); break; case opWrap2: SetRaw(a, signal_wrap2_xf(g, slotRawObject(a), slotRawInt(b))); break; case opExcess: SetRaw(a, signal_excess_xf(g, slotRawObject(a), slotRawInt(b))); break; case opFirstArg: SetRaw(a, slotRawObject(a)); break; default: goto send_normal_2; } break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: if (IS_BINARY_BOOL_OP(opcode)) SetBool(a, opcode == opNE); else SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) { switch (opcode) { case opAdd: SetRaw(a, signal_add_xx(g, slotRawObject(a), slotRawObject(b))); break; case opSub: SetRaw(a, signal_sub_xx(g, slotRawObject(a), slotRawObject(b))); break; case opMul: SetRaw(a, signal_mul_xx(g, slotRawObject(a), slotRawObject(b))); break; case opIDiv: SetRaw(a, signal_div_xx(g, slotRawObject(a), slotRawObject(b))); break; case opFDiv: SetRaw(a, signal_div_xx(g, slotRawObject(a), slotRawObject(b))); break; case opEQ: SetBool(a, signal_equal_xx(g, slotRawObject(a), slotRawObject(b))); break; case opNE: SetBool(a, !signal_equal_xx(g, slotRawObject(a), slotRawObject(b))); break; case opMin: SetRaw(a, signal_min_xx(g, slotRawObject(a), slotRawObject(b))); break; case opMax: SetRaw(a, signal_max_xx(g, slotRawObject(a), slotRawObject(b))); break; case opRing1: SetRaw(a, signal_ring1_xx(g, slotRawObject(a), slotRawObject(b))); break; case opRing2: SetRaw(a, signal_ring2_xx(g, slotRawObject(a), slotRawObject(b))); break; case opRing3: SetRaw(a, signal_ring3_xx(g, slotRawObject(a), slotRawObject(b))); break; case opRing4: SetRaw(a, signal_ring4_xx(g, slotRawObject(a), slotRawObject(b))); break; case opDifSqr: SetRaw(a, signal_difsqr_xx(g, slotRawObject(a), slotRawObject(b))); break; case opSumSqr: SetRaw(a, signal_sumsqr_xx(g, slotRawObject(a), slotRawObject(b))); break; case opSqrSum: SetRaw(a, signal_sqrsum_xx(g, slotRawObject(a), slotRawObject(b))); break; case opSqrDif: SetRaw(a, signal_sqrdif_xx(g, slotRawObject(a), slotRawObject(b))); break; case opAbsDif: SetRaw(a, signal_absdif_xx(g, slotRawObject(a), slotRawObject(b))); break; case opThresh: SetRaw(a, signal_thresh_xx(g, slotRawObject(a), slotRawObject(b))); break; case opAMClip: SetRaw(a, signal_amclip_xx(g, slotRawObject(a), slotRawObject(b))); break; case opScaleNeg: SetRaw(a, signal_scaleneg_xx(g, slotRawObject(a), slotRawObject(b))); break; case opClip2: SetRaw(a, signal_clip2_xx(g, slotRawObject(a), slotRawObject(b))); break; case opFold2: SetRaw(a, signal_fold2_xx(g, slotRawObject(a), slotRawObject(b))); break; case opWrap2: SetRaw(a, signal_wrap2_xx(g, slotRawObject(a), slotRawObject(b))); break; case opExcess: SetRaw(a, signal_excess_xx(g, slotRawObject(a), slotRawObject(b))); break; case opFirstArg: SetRaw(a, slotRawObject(a)); break; default: goto send_normal_2; } } else goto send_normal_2; break; default: // double switch (opcode) { case opAdd: SetRaw(a, signal_add_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opSub: SetRaw(a, signal_sub_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opMul: SetRaw(a, signal_mul_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opIDiv: SetRaw(a, signal_div_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opFDiv: SetRaw(a, signal_div_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opEQ: SetFalse(a); break; case opNE: SetTrue(a); break; case opMin: SetRaw(a, signal_min_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opMax: SetRaw(a, signal_max_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opFill: SetRaw(a, signal_fill(slotRawObject(a), slotRawFloat(b))); break; case opRing1: SetRaw(a, signal_ring1_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opRing2: SetRaw(a, signal_ring2_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opRing3: SetRaw(a, signal_ring3_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opRing4: SetRaw(a, signal_ring4_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opDifSqr: SetRaw(a, signal_difsqr_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opSumSqr: SetRaw(a, signal_sumsqr_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opSqrSum: SetRaw(a, signal_sqrsum_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opSqrDif: SetRaw(a, signal_sqrdif_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opAbsDif: SetRaw(a, signal_absdif_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opThresh: SetRaw(a, signal_thresh_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opAMClip: SetRaw(a, signal_amclip_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opScaleNeg: SetRaw(a, signal_scaleneg_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opClip2: SetRaw(a, signal_clip2_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opFold2: SetRaw(a, signal_fold2_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opWrap2: SetRaw(a, signal_wrap2_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opExcess: SetRaw(a, signal_excess_xf(g, slotRawObject(a), slotRawFloat(b))); break; case opFirstArg: SetRaw(a, slotRawObject(a)); break; default: goto send_normal_2; } break; } } else { goto send_normal_2; } } break; default: { // double switch (GetTag(b)) { case tagInt: switch (opcode) { case opAdd: SetRaw(a, slotRawFloat(a) + slotRawInt(b)); break; case opSub: SetRaw(a, slotRawFloat(a) - slotRawInt(b)); break; case opMul: SetRaw(a, slotRawFloat(a) * slotRawInt(b)); break; case opIDiv: SetInt(a, (long)floor(slotRawFloat(a) / slotRawInt(b))); break; case opFDiv: SetRaw(a, slotRawFloat(a) / slotRawInt(b)); break; case opMod: SetRaw(a, sc_mod(slotRawFloat(a), (double)slotRawInt(b))); break; case opEQ: SetBool(a, slotRawFloat(a) == slotRawInt(b)); break; case opNE: SetBool(a, slotRawFloat(a) != slotRawInt(b)); break; case opLT: SetBool(a, slotRawFloat(a) < slotRawInt(b)); break; case opGT: SetBool(a, slotRawFloat(a) > slotRawInt(b)); break; case opLE: SetBool(a, slotRawFloat(a) <= slotRawInt(b)); break; case opGE: SetBool(a, slotRawFloat(a) >= slotRawInt(b)); break; // case opIdentical : SetFalse(a); break; // case opNotIdentical : SetTrue(a); break; case opMin: SetRaw(a, sc_min(slotRawFloat(a), (double)slotRawInt(b))); break; case opMax: SetRaw(a, sc_max(slotRawFloat(a), (double)slotRawInt(b))); break; case opRound: SetRaw(a, sc_round(slotRawFloat(a), (double)slotRawInt(b))); break; case opRoundUp: SetRaw(a, sc_roundUp(slotRawFloat(a), (double)slotRawInt(b))); break; case opTrunc: SetRaw(a, sc_trunc(slotRawFloat(a), (double)slotRawInt(b))); break; case opAtan2: SetRaw(a, atan2(slotRawFloat(a), slotRawInt(b))); break; case opHypot: SetRaw(a, hypot(slotRawFloat(a), slotRawInt(b))); break; case opHypotx: SetRaw(a, hypotx(slotRawFloat(a), slotRawInt(b))); break; case opPow: SetRaw(a, pow(slotRawFloat(a), (double)slotRawInt(b))); break; case opRing1: SetRaw(a, sc_ring1(slotRawFloat(a), (double)slotRawInt(b))); break; case opRing2: SetRaw(a, sc_ring2(slotRawFloat(a), (double)slotRawInt(b))); break; case opRing3: SetRaw(a, sc_ring3(slotRawFloat(a), (double)slotRawInt(b))); break; case opRing4: SetRaw(a, sc_ring4(slotRawFloat(a), (double)slotRawInt(b))); break; case opDifSqr: SetRaw(a, sc_difsqr(slotRawFloat(a), (double)slotRawInt(b))); break; case opSumSqr: SetRaw(a, sc_sumsqr(slotRawFloat(a), (double)slotRawInt(b))); break; case opSqrSum: SetRaw(a, sc_sqrsum(slotRawFloat(a), (double)slotRawInt(b))); break; case opSqrDif: SetRaw(a, sc_sqrdif(slotRawFloat(a), (double)slotRawInt(b))); break; case opAbsDif: SetRaw(a, sc_abs(slotRawFloat(a) - slotRawInt(b))); break; case opThresh: SetRaw(a, sc_thresh(slotRawFloat(a), slotRawInt(b))); break; case opAMClip: SetRaw(a, sc_amclip(slotRawFloat(a), (double)slotRawInt(b))); break; case opScaleNeg: SetRaw(a, sc_scaleneg(slotRawFloat(a), (double)slotRawInt(b))); break; case opClip2: SetRaw(a, sc_clip2(slotRawFloat(a), (double)slotRawInt(b))); break; case opFold2: SetRaw(a, sc_fold2(slotRawFloat(a), (double)slotRawInt(b))); break; case opWrap2: SetRaw(a, sc_wrap2(slotRawFloat(a), (double)slotRawInt(b))); break; case opExcess: SetRaw(a, sc_excess(slotRawFloat(a), (double)slotRawInt(b))); break; case opFirstArg: SetRaw(a, slotRawFloat(a)); break; case opRandRange: SetRaw(a, slotRawFloat(a) + g->rgen->frand() * (slotRawInt(b) - slotRawFloat(a))); break; case opExpRandRange: SetRaw(a, g->rgen->exprandrng(slotRawFloat(a), slotRawInt(b))); break; default: goto send_normal_2; } break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: if (IS_BINARY_BOOL_OP(opcode)) SetBool(a, opcode == opNE); else SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) { switch (opcode) { case opAdd: SetObject(a, signal_add_xf(g, slotRawObject(b), slotRawFloat(a))); break; case opSub: SetObject(a, signal_sub_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opMul: SetObject(a, signal_mul_xf(g, slotRawObject(b), slotRawFloat(a))); break; case opIDiv: SetObject(a, signal_div_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opFDiv: SetObject(a, signal_div_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opEQ: SetFalse(a); break; case opNE: SetTrue(a); break; case opMin: SetObject(a, signal_min_xf(g, slotRawObject(b), slotRawFloat(a))); break; case opMax: SetObject(a, signal_max_xf(g, slotRawObject(b), slotRawFloat(a))); break; case opRing1: SetObject(a, signal_ring1_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opRing2: SetObject(a, signal_ring2_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opRing3: SetObject(a, signal_ring3_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opRing4: SetObject(a, signal_ring4_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opDifSqr: SetObject(a, signal_difsqr_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opSumSqr: SetObject(a, signal_sumsqr_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opSqrSum: SetObject(a, signal_sqrsum_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opSqrDif: SetObject(a, signal_sqrdif_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opAbsDif: SetObject(a, signal_absdif_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opThresh: SetObject(a, signal_thresh_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opAMClip: SetObject(a, signal_amclip_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opScaleNeg: SetObject(a, signal_scaleneg_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opClip2: SetObject(a, signal_clip2_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opFold2: SetObject(a, signal_fold2_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opWrap2: SetObject(a, signal_wrap2_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opExcess: SetObject(a, signal_excess_fx(g, slotRawFloat(a), slotRawObject(b))); break; case opFirstArg: SetObject(a, slotRawObject(a)); break; default: goto send_normal_2; } } else goto send_normal_2; break; default: // double switch (opcode) { case opAdd: SetRaw(a, slotRawFloat(a) + slotRawFloat(b)); break; case opSub: SetRaw(a, slotRawFloat(a) - slotRawFloat(b)); break; case opMul: SetRaw(a, slotRawFloat(a) * slotRawFloat(b)); break; case opIDiv: SetInt(a, (long)floor(slotRawFloat(a) / slotRawFloat(b))); break; case opFDiv: SetRaw(a, slotRawFloat(a) / slotRawFloat(b)); break; case opMod: SetRaw(a, sc_mod(slotRawFloat(a), slotRawFloat(b))); break; case opEQ: SetBool(a, slotRawFloat(a) == slotRawFloat(b)); break; case opNE: SetBool(a, slotRawFloat(a) != slotRawFloat(b)); break; case opLT: SetBool(a, slotRawFloat(a) < slotRawFloat(b)); break; case opGT: SetBool(a, slotRawFloat(a) > slotRawFloat(b)); break; case opLE: SetBool(a, slotRawFloat(a) <= slotRawFloat(b)); break; case opGE: SetBool(a, slotRawFloat(a) >= slotRawFloat(b)); break; // case opIdentical : SetBool(a, slotRawFloat(a) == slotRawFloat(b)); break; // case opNotIdentical : SetBool(a, slotRawFloat(a) != slotRawFloat(b)); break; case opMin: SetRaw(a, sc_min(slotRawFloat(a), slotRawFloat(b))); break; case opMax: SetRaw(a, sc_max(slotRawFloat(a), slotRawFloat(b))); break; case opRound: SetRaw(a, sc_round(slotRawFloat(a), slotRawFloat(b))); break; case opRoundUp: SetRaw(a, sc_roundUp(slotRawFloat(a), slotRawFloat(b))); break; case opTrunc: SetRaw(a, sc_trunc(slotRawFloat(a), slotRawFloat(b))); break; case opAtan2: SetRaw(a, atan2(slotRawFloat(a), slotRawFloat(b))); break; case opHypot: SetRaw(a, hypot(slotRawFloat(a), slotRawFloat(b))); break; case opHypotx: SetRaw(a, hypotx(slotRawFloat(a), slotRawFloat(b))); break; case opPow: SetRaw(a, pow(slotRawFloat(a), slotRawFloat(b))); break; case opRing1: SetRaw(a, sc_ring1(slotRawFloat(a), slotRawFloat(b))); break; case opRing2: SetRaw(a, sc_ring2(slotRawFloat(a), slotRawFloat(b))); break; case opRing3: SetRaw(a, sc_ring3(slotRawFloat(a), slotRawFloat(b))); break; case opRing4: SetRaw(a, sc_ring4(slotRawFloat(a), slotRawFloat(b))); break; case opDifSqr: SetRaw(a, sc_difsqr(slotRawFloat(a), slotRawFloat(b))); break; case opSumSqr: SetRaw(a, sc_sumsqr(slotRawFloat(a), slotRawFloat(b))); break; case opSqrSum: SetRaw(a, sc_sqrsum(slotRawFloat(a), slotRawFloat(b))); break; case opSqrDif: SetRaw(a, sc_sqrdif(slotRawFloat(a), slotRawFloat(b))); break; case opAbsDif: SetRaw(a, sc_abs(slotRawFloat(a) - slotRawFloat(b))); break; case opThresh: SetRaw(a, sc_thresh(slotRawFloat(a), slotRawFloat(b))); break; case opAMClip: SetRaw(a, sc_amclip(slotRawFloat(a), slotRawFloat(b))); break; case opScaleNeg: SetRaw(a, sc_scaleneg(slotRawFloat(a), slotRawFloat(b))); break; case opClip2: SetRaw(a, sc_clip2(slotRawFloat(a), slotRawFloat(b))); break; case opFold2: SetRaw(a, sc_fold2(slotRawFloat(a), slotRawFloat(b))); break; case opWrap2: SetRaw(a, sc_wrap2(slotRawFloat(a), slotRawFloat(b))); break; case opExcess: SetRaw(a, sc_excess(slotRawFloat(a), slotRawFloat(b))); break; case opFirstArg: SetRaw(a, slotRawFloat(a)); break; case opRandRange: SetRaw(a, slotRawFloat(a) + g->rgen->frand() * (slotRawFloat(b) - slotRawFloat(a))); break; case opExpRandRange: SetRaw(a, g->rgen->exprandrng(slotRawFloat(a), slotRawFloat(b))); break; default: goto send_normal_2; } break; } } break; } g->sp = a; // drop g->numpop = 0; #if TAILCALLOPTIMIZE g->tailCall = 0; #endif return errNone; send_normal_2: if (isPrimitive) // special case flag meaning it is a primitive return errFailed; // arguments remain on the stack msg = gSpecialBinarySelectors[opcode]; sendMessage(g, msg, numArgsPushed, 0); return errNone; }
64,047
C++
.cpp
1,695
22.822419
120
0.469122
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,844
PyrSignal.cpp
supercollider_supercollider/lang/LangSource/PyrSignal.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* compound formulas : amclip out = B<=0 ? 0 : A*B; // two quadrant amplitude modulation ring1 out = A*(B+1) = A*B + A; // amplitude modulation of a by b. ring2 out = A*B + A + B; // ring modulation plus both original signals ring3 out = A*A*B; // ring modulation variant ring4 out = A*A*B - A*B*B; // ring modulation variant difsqr out = A*A - B*B; // difference of squares sumsqr out = A*A + B*B; // sum of squares sqrdif out = (A - B)^2 // square of the difference = a^2 + b^2 - 2ab sqrsum out = (A + B)^2 // square of the sum = a^2 + b^2 + 2ab */ #include <math.h> #include <stdlib.h> #include <string.h> #include "PyrSignal.h" #include "PyrKernel.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "SCBase.h" #include "InitAlloc.h" PyrObject* newPyrSignal(VMGlobals* g, long size) { PyrObject* signal; long numbytes = size * sizeof(float); signal = (PyrObject*)g->gc->New(numbytes, 0, obj_float, true); if (signal) { signal->classptr = class_signal; signal->size = size; } // note: signal is filled with garbage return signal; } /*PyrObject* newPyrSignalFrom(VMGlobals *g, PyrObject* inSignal, long size) { PyrObject *signal; double *pslot, *qslot, *endptr; long set, m, mmax; long numbytes = size * sizeof(float); signal = (PyrObject*)g->gc->New(numbytes, 0, obj_float, true); signal->classptr = inSignal->classptr; signal->size = size; return signal; } */ PyrObject* signal_fill(PyrObject* outSignal, float inValue) { float* out = (float*)(outSignal->slots) - 1; UNROLL_CODE(outSignal->size, out, *++out = inValue;); return outSignal; } PyrObject* signal_scale(PyrObject* outSignal, float inValue) { if (inValue != 1.f) { float* out = (float*)(outSignal->slots) - 1; UNROLL_CODE(outSignal->size, out, *++out *= inValue;) } return outSignal; } PyrObject* signal_offset(PyrObject* outSignal, float inValue) { if (inValue != 0.f) { float* out = (float*)(outSignal->slots) - 1; UNROLL_CODE(outSignal->size, out, *++out += inValue;) } return outSignal; } PyrObject* signal_add_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP1(+); } PyrObject* signal_mul_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP1(*); } PyrObject* signal_sub_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(*++c = *++a - *++b;); } PyrObject* signal_ring1_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; *++c = *a * *++b + *a;); } PyrObject* signal_ring2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a * *b + *a + *b;); } PyrObject* signal_ring3_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; *++c = *a * *a * *++b;); } PyrObject* signal_ring4_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a * *a * *b - *a * *b * *b;); } PyrObject* signal_thresh_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a < *b ? 0.f : *a;); } PyrObject* signal_amclip_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *b <= 0.f ? 0.f : *a * *b;); } PyrObject* signal_div_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(*++c = *++a / *++b;); } PyrObject* signal_difsqr_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *c = *a * *a - *b * *b;); } PyrObject* signal_sumsqr_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *c = *a * *a + *b * *b;); } PyrObject* signal_sqrsum_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { float z; BINOP_LOOP2(z = *++a + *++b; *++c = z * z;); } PyrObject* signal_sqrdif_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { float z; BINOP_LOOP2(z = *++a - *++b; *++c = z * z;); } PyrObject* signal_absdif_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(*++c = fabs(*++a - *++b);); } PyrObject* signal_add_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); if (inb == 0.f) { float* a = (float*)(ina->slots); memcpy((float*)(outc->slots), a, ina->size * sizeof(float)); } else { float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = *++a + inb;) } return outc; } PyrObject* signal_sub_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); if (inb == 0.f) { float* a = (float*)(ina->slots); memcpy((float*)(outc->slots), a, ina->size * sizeof(float)); } else { float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = *++a - inb;) } return outc; } PyrObject* signal_mul_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); if (inb == 1.f) { float* a = (float*)(ina->slots); memcpy((float*)(outc->slots), a, ina->size * sizeof(float)); } else { float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = *++a * inb;) } return outc; } PyrObject* signal_ring1_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++a; *++c = *a * inb + *a;) return outc; } PyrObject* signal_ring2_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++a; *++c = *a * inb + *a + inb;) return outc; } PyrObject* signal_ring3_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++a; *++c = *a * *a * inb;) return outc; } PyrObject* signal_ring4_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; float inb2 = inb * inb; UNROLL_CODE(outc->size, c, ++a; *++c = *a * *a * inb + *a * inb2;) return outc; } PyrObject* signal_thresh_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++a; *++c = *a < inb ? 0.f : *a;) return outc; } PyrObject* signal_amclip_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* res; PyrObject* outc = newPyrSignal(g, ina->size); if (inb <= 0.f) res = signal_fill(outc, 0.f); else res = signal_scale(outc, inb); return res; } PyrObject* signal_div_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); if (inb == 1.f) { float* a = (float*)(ina->slots); memcpy((float*)(outc->slots), a, ina->size * sizeof(float)); } else { float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; inb = 1.f / inb; UNROLL_CODE(outc->size, c, *++c = *++a * inb;) } return outc; } PyrObject* signal_difsqr_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; inb = inb * inb; UNROLL_CODE(outc->size, c, ++a; *++c = *a * *a - inb;) return outc; } PyrObject* signal_sumsqr_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; inb = inb * inb; UNROLL_CODE(outc->size, c, ++a; *++c = *a * *a + inb;) return outc; } PyrObject* signal_sqrsum_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; float temp; UNROLL_CODE(outc->size, c, ++a; temp = *a + inb; *++c = temp * temp;) return outc; } PyrObject* signal_sqrdif_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; float temp; UNROLL_CODE(outc->size, c, ++a; temp = *a - inb; *++c = temp * temp;) return outc; } PyrObject* signal_absdif_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++a; *++c = fabs(*a - inb);) return outc; } PyrObject* signal_ring1_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = ina * *++b + ina;) return outc; } PyrObject* signal_ring2_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++b; *++c = ina * *b + ina + *b;) return outc; } PyrObject* signal_ring3_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; float ina2 = ina * ina; UNROLL_CODE(outc->size, c, *++c = ina2 * *++b;) return outc; } PyrObject* signal_ring4_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; float ina2 = ina * ina; UNROLL_CODE(outc->size, c, ++b; *++c = ina2 * *b - ina * *b * *b;) return outc; } PyrObject* signal_thresh_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = ina < *b ? 0.f : ina;) return outc; } PyrObject* signal_amclip_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = *b <= 0.f ? 0.f : ina * *b;) return outc; } PyrObject* signal_sub_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = ina - *++b;) return outc; } PyrObject* signal_div_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, *++c = ina / *++b;) return outc; } PyrObject* signal_difsqr_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; ina = ina * ina; UNROLL_CODE(outc->size, c, ++b; *++c = ina - *b * *b;) return outc; } PyrObject* signal_sumsqr_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; ina = ina * ina; UNROLL_CODE(outc->size, c, ++b; *++c = ina + *b * *b;) return outc; } PyrObject* signal_sqrsum_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float temp; float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++b; temp = ina + *b; *++c = temp * temp;) return outc; } PyrObject* signal_sqrdif_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float temp; float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++b; temp = ina - *b; *++c = temp * temp;) return outc; } PyrObject* signal_absdif_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL_CODE(outc->size, c, ++b; *++c = fabs(ina - *b);) return outc; } PyrObject* signal_min_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a < *b ? *a : *b;); } PyrObject* signal_max_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a > *b ? *a : *b;); } PyrObject* signal_scaleneg_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a < 0.f ? *a * *b : *a;); } PyrObject* signal_clip2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a > *b ? *b : (*a < -*b ? -*b : *a);); } PyrObject* signal_fold2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = sc_fold(*a, -*b, *b);); } PyrObject* signal_wrap2_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = sc_wrap(*a, -*b, *b);); } PyrObject* signal_excess_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { BINOP_LOOP2(++a; ++b; *++c = *a > *b ? *a - *b : (*a < -*b ? *a + *b : 0.f);); } bool signal_equal_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { if (ina->size != inb->size) return false; if (slotRawSymbol(&ina->slots[kSignalRate]) != slotRawSymbol(&inb->slots[kSignalRate])) return false; float* a = (float*)(ina->slots); float* b = (float*)(inb->slots); for (int i = 0; i < ina->size; i++) { if (a[i] != b[i]) { return false; } } return true; } PyrObject* signal_min_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = *a < inb ? *a : inb;) return outc; } PyrObject* signal_max_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = *a > inb ? *a : inb;) return outc; } PyrObject* signal_scaleneg_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = *a < 0.f ? *a * inb : *a;) return outc; } PyrObject* signal_clip2_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = *a > inb ? inb : (*a < -inb ? -inb : *a);) return outc; } PyrObject* signal_fold2_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = sc_fold(*a, -inb, inb);) return outc; } PyrObject* signal_wrap2_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = sc_wrap(*a, -inb, inb);) return outc; } PyrObject* signal_excess_xf(VMGlobals* g, PyrObject* ina, float inb) { PyrObject* outc = newPyrSignal(g, ina->size); float* a = (float*)(ina->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++a; *++c = *a > inb ? *a - inb : (*a < -inb ? *a + inb : 0.f);) return outc; } PyrObject* signal_scaleneg_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; if (ina < 0.f) { UNROLL1_CODE(outc->size, c, *++c = ina * *++b;); } else { UNROLL1_CODE(outc->size, c, *++c = ina;); } return outc; } PyrObject* signal_clip2_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = ina > *b ? *b : (ina < -*b ? -*b : ina);) return outc; } PyrObject* signal_fold2_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = sc_fold(ina, -*b, *b);) return outc; } PyrObject* signal_wrap2_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = sc_wrap(ina, -*b, *b);) return outc; } PyrObject* signal_excess_fx(VMGlobals* g, float ina, PyrObject* inb) { PyrObject* outc = newPyrSignal(g, inb->size); float* b = (float*)(inb->slots) - 1; float* c = (float*)(outc->slots) - 1; UNROLL1_CODE(outc->size, c, ++b; *++c = ina > *b ? ina - *b : (ina < -*b ? ina + *b : 0.f);) return outc; } PyrObject* signal_invert(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL_CODE(inPyrSignal->size, out, *++out = -*++in;) return outc; } PyrObject* signal_recip(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL_CODE(inPyrSignal->size, out, *++out = 1.f / *++in;) return outc; } PyrObject* signal_squared(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL_CODE(inPyrSignal->size, out, ++in; *++out = *in * *in;) return outc; } PyrObject* signal_cubed(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL_CODE(inPyrSignal->size, out, ++in; *++out = *in * *in * *in;) return outc; } // PowerPC has a fast fabs instruction PyrObject* signal_abs(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL_CODE(inPyrSignal->size, out, *++out = fabs(*++in);) return outc; } float signal_findpeak(PyrObject* inPyrSignal) { float* out = (float*)(inPyrSignal->slots) - 1; float peak = 0.f; float z; UNROLL1_CODE(inPyrSignal->size, out, ++out; z = fabs(*out); peak = z > peak ? z : peak;) return peak; } PyrObject* signal_normalize_transfer_fn(PyrObject* inPyrSignal) { float *out, scale, offset, x, maxval; long length, halflength; maxval = 0.0; out = (float*)(inPyrSignal->slots) - 1; length = inPyrSignal->size; halflength = length >> 1; offset = (out[halflength - 1] + out[halflength]) * 0.5; UNROLL1_CODE(inPyrSignal->size, out, ++out; x = *out - offset; x = (x < 0.) ? -x : x; if (x > maxval) maxval = x;); if (maxval) { out = (float*)(inPyrSignal->slots) - 1; scale = 1.0 / maxval; UNROLL1_CODE(inPyrSignal->size, out, ++out; *out = (*out - offset) * scale;); } return inPyrSignal; } float signal_integral(PyrObject* inPyrSignal) { float* out = (float*)(inPyrSignal->slots) - 1; float sum = 0.f; UNROLL1_CODE(inPyrSignal->size, out, sum += *++out;) return sum; } PyrObject* signal_sign(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, ++in; *++out = *in < 0.f ? -1.f : (*in > 0.f ? 1.f : 0.f);) return outc; } PyrObject* signal_negative(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = *++in < 0.f ? 1.f : 0.f;) return outc; } PyrObject* signal_positive(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = *++in >= 0.f ? 1.f : 0.f;) return outc; } PyrObject* signal_strictly_positive(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = *++in > 0.f ? 1.f : 0.f;) return outc; } PyrObject* signal_nyqring(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; float* endptr = out + inPyrSignal->size; switch (inPyrSignal->size & 3) { while (out < endptr) { *++out = -*++in; case 3: *++out = *++in; case 2: *++out = -*++in; case 1: *++out = *++in; case 0:; } } return outc; } PyrObject* signal_clip_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; float* endptr = out + inPyrSignal->size; while (out < endptr) { ++in; *++out = *in < lo ? lo : (*in > hi ? hi : *in); } return outc; } PyrObject* signal_clip_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc) { PyrObject* outd; float *a, *b, *c, *d, *endptr; long minsize = sc_min(ina->size, inb->size); minsize = sc_min(minsize, inc->size); outd = newPyrSignal(g, minsize); a = (float*)(ina->slots) - 1; b = (float*)(inb->slots) - 1; c = (float*)(inc->slots) - 1; d = (float*)(outd->slots) - 1; endptr = a + minsize; UNROLL1_CODE(outd->size, d, ++a; ++b; ++c; *++d = *a < *b ? *b : (*a > *c ? *c : *a);); return outd; } /// WRAP AND FOLD ARE STILL INCORRECT ! PyrObject* signal_wrap_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi) { float* out = (float*)(inPyrSignal->slots) - 1; float* endptr = out + inPyrSignal->size; while (out < endptr) { ++out; *out = sc_wrap(*out, lo, hi); } return inPyrSignal; } PyrObject* signal_wrap_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc) { PyrObject* outd; float *a, *b, *c, *d, *endptr; long minsize = sc_min(ina->size, inb->size); minsize = sc_min(minsize, inc->size); outd = newPyrSignal(g, minsize); a = (float*)(ina->slots) - 1; b = (float*)(inb->slots) - 1; c = (float*)(inc->slots) - 1; d = (float*)(outd->slots) - 1; endptr = d + outd->size; while (d < endptr) { a++; b++; c++; d++; ++d; *d = sc_wrap(*a, *b, *c); } return outd; } PyrObject* signal_fold_f(VMGlobals* g, PyrObject* inPyrSignal, float lo, float hi) { float* out = (float*)(inPyrSignal->slots) - 1; float* endptr = out + inPyrSignal->size; while (out < endptr) { ++out; *out = sc_fold(*out, lo, hi); } return inPyrSignal; } PyrObject* signal_fold_x(VMGlobals* g, PyrObject* ina, PyrObject* inb, PyrObject* inc) { PyrObject* outd; float *a, *b, *c, *d, *endptr; long minsize = sc_min(ina->size, inb->size); minsize = sc_min(minsize, inc->size); outd = newPyrSignal(g, minsize); a = (float*)(ina->slots) - 1; b = (float*)(inb->slots) - 1; c = (float*)(inc->slots) - 1; d = (float*)(outd->slots) - 1; endptr = d + outd->size; while (d < endptr) { a++; b++; c++; d++; *d = sc_fold(*a, *b, *c); } return outd; } PyrObject* signal_log(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = log(*++in);) return outc; } PyrObject* signal_log2(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = sc_log2(*++in);) return outc; } PyrObject* signal_log10(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = log10(*++in);) return outc; } PyrObject* signal_sin(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = sin(*++in);) return outc; } PyrObject* signal_cos(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = cos(*++in);) return outc; } PyrObject* signal_tan(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = tan(*++in);) return outc; } PyrObject* signal_sinh(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = sinh(*++in);) return outc; } PyrObject* signal_cosh(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = cosh(*++in);) return outc; } PyrObject* signal_tanh(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = tanh(*++in);) return outc; } PyrObject* signal_tanh_ds(PyrObject* inPyrSignal) { float* out = (float*)(inPyrSignal->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, ++out; *out = tanh(*out);) return inPyrSignal; } PyrObject* signal_asin(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = asin(*++in);) return outc; } PyrObject* signal_acos(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = acos(*++in);) return outc; } PyrObject* signal_atan(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = atan(*++in);) return outc; } PyrObject* signal_exp(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = exp(*++in);) return outc; } PyrObject* signal_sqrt(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; UNROLL1_CODE(inPyrSignal->size, out, *++out = sqrt(*++in);) return outc; } PyrObject* signal_distort(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; float* endptr = out + inPyrSignal->size; while (out < endptr) { float z = *++in; if (z < 0.f) *++out = z / (1.f - z); else *++out = z / (1.f + z); } return outc; } PyrObject* signal_softclip(VMGlobals* g, PyrObject* inPyrSignal) { float* in = (float*)(inPyrSignal->slots) - 1; PyrObject* outc = newPyrSignal(g, inPyrSignal->size); float* out = (float*)(outc->slots) - 1; float* endptr = out + inPyrSignal->size; while (out < endptr) { float z = *++in; if (z < -0.5f) *++out = (-z - .25f) / z; else if (z > 0.5f) *++out = (z - .25f) / z; else *++out = z; } return outc; } PyrObject* signal_rotate(VMGlobals* g, PyrObject* ina, int rot) { long i, j; PyrObject* outc = newPyrSignal(g, ina->size); float* a0 = (float*)(ina->slots) - 1; // float *a = a0 + sc_mod(rot, ina->size); float* a = a0 + sc_mod(0 - rot, ina->size); float* aend = a0 + ina->size; float* c = (float*)(outc->slots) - 1; long nsmps = outc->size; for (i = 0, j = rot; i < nsmps; i++, j++) { *++c = *++a; if (a >= aend) a = a0; } return outc; } PyrObject* signal_reverse_range(PyrObject* ina, long start, long end) { long size = ina->size; long size2; long i; start = sc_max(0, start); end = sc_min(end + 1, size); size = end - start; size2 = size >> 1; float* a = (float*)(ina->slots) - 1 + start; // float *b = (float*)(ina->slots) - 1 + end; float* b = (float*)(ina->slots) + end; float temp; for (i = 0; i < size2; ++i) { temp = *++a; *a = *--b; *b = temp; } return ina; } PyrObject* signal_normalize_range(PyrObject* ina, long start, long end) { long size = ina->size; long i; float z, scale, maxlevel; float *a0, *a; start = sc_max(0, start); end = sc_min(end + 1, size); size = end - start; a0 = (float*)(ina->slots) - 1 + start; a = a0; maxlevel = 0.f; for (i = 0; i < size; ++i) { z = fabs(*++a); if (z > maxlevel) maxlevel = z; } a = a0; if (maxlevel != 0.f) { scale = 1. / maxlevel; for (i = 0; i < size; ++i) { z = *++a; *a = scale * z; } } return ina; } PyrObject* signal_invert_range(PyrObject* ina, long start, long end) { long size = ina->size; long i; float z; start = sc_max(0, start); end = sc_min(end, size); size = end - start + 1; float* a = (float*)(ina->slots) - 1 + start; for (i = 0; i < size; ++i) { z = *++a; *a = -z; } return ina; } PyrObject* signal_fade_range(PyrObject* ina, long start, long end, float lvl0, float lvl1) { long size = ina->size; long i; float z, level, slope; start = sc_max(0, start); end = sc_min(end + 1, size); size = end - start; float* a = (float*)(ina->slots) - 1 + start; slope = (lvl1 - lvl0) / size; level = lvl0; for (i = 0; i < size; ++i) { z = *++a; *a = z * level; level += slope; } return ina; } PyrObject* signal_overdub(VMGlobals* g, PyrObject* ina, PyrObject* inb, long index) { float *a, *b; long len; if (index > 0) { a = (float*)(ina->slots) + index - 1; b = (float*)(inb->slots) - 1; len = sc_min(inb->size, ina->size - index); } else { a = (float*)(ina->slots) - 1; b = (float*)(inb->slots) - index - 1; len = sc_min(ina->size, inb->size + index); } UNROLL_CODE(len, a, *++a += *++b;); return ina; } PyrObject* signal_overwrite(VMGlobals* g, PyrObject* ina, PyrObject* inb, long index) { float *a, *b; long len; if (index > 0) { a = (float*)(ina->slots) + index - 1; b = (float*)(inb->slots) - 1; len = sc_min(inb->size, ina->size - index); } else { a = (float*)(ina->slots) - 1; b = (float*)(inb->slots) - index - 1; len = sc_min(ina->size, inb->size + index); } UNROLL_CODE(len, a, *++a = *++b;); return ina; }
34,909
C++
.cpp
917
33.400218
119
0.591051
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
29,845
AdvancingAllocPool.cpp
supercollider_supercollider/lang/LangSource/AdvancingAllocPool.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "AdvancingAllocPool.h" #include "SC_AllocPool.h" //#include <assert.h> AdvancingAllocPool::AdvancingAllocPool() { mAllocPool = nullptr; mInitSize = 0; mGrowSize = 0; mTooBig = 0; mCurSize = 0; mChunks = nullptr; mFatties = nullptr; } void AdvancingAllocPool::Init(AllocPool* inAllocPool, size_t initSize, size_t growSize, size_t tooBigSize) { mAllocPool = inAllocPool; mInitSize = initSize; mGrowSize = growSize; mTooBig = tooBigSize; mChunks = nullptr; AddChunk(initSize); mFatties = nullptr; // assert(SanityCheck()); } void AdvancingAllocPool::AddChunk(size_t inSize) { size_t chunkSize = sizeof(AdvancingAllocPoolChunkHdr) + inSize; AdvancingAllocPoolChunk* chunk = (AdvancingAllocPoolChunk*)mAllocPool->Alloc(chunkSize); FailNil(chunk); chunk->mNext = mChunks; mChunks = chunk; chunk->mSize = mGrowSize; mCurSize = 0; } void* AdvancingAllocPool::Alloc(size_t reqsize) { // assert(SanityCheck()); // assert(mAllocPool); size_t size = (reqsize + 15) & ~15; // round up to 16 byte alignment if (size < mTooBig) { if (!mChunks) AddChunk(mInitSize); else if (mCurSize + size > mChunks->mSize) AddChunk(mGrowSize); char* space = mChunks->mSpace + mCurSize; mCurSize += size; // assert(SanityCheck()); return (void*)space; } else { size_t chunkSize = sizeof(AdvancingAllocPoolChunkHdr) + size; AdvancingAllocPoolChunk* fatty = (AdvancingAllocPoolChunk*)mAllocPool->Alloc(chunkSize); FailNil(fatty); fatty->mNext = mFatties; mFatties = fatty; fatty->mSize = size; // assert(SanityCheck()); return (void*)fatty->mSpace; } } void AdvancingAllocPool::FreeAll() { // assert(SanityCheck()); AdvancingAllocPoolChunk *chunk, *next; for (chunk = mChunks; chunk; chunk = next) { next = chunk->mNext; mAllocPool->Free(chunk); } for (chunk = mFatties; chunk; chunk = next) { next = chunk->mNext; mAllocPool->Free(chunk); } mChunks = nullptr; mFatties = nullptr; mCurSize = 0; // assert(SanityCheck()); } bool AdvancingAllocPool::SanityCheck() { AdvancingAllocPoolChunk *chunk, *next; for (chunk = mChunks; chunk; chunk = next) { next = chunk->mNext; mAllocPool->DoCheckInUseChunk(AllocPool::MemToChunk(chunk)); } for (chunk = mFatties; chunk; chunk = next) { next = chunk->mNext; mAllocPool->DoCheckInUseChunk(AllocPool::MemToChunk(chunk)); } return true; }
3,513
C++
.cpp
99
29.979798
108
0.678529
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false